http:// msdn.microsoft.com/en-us/library/ms378956(v=sql.90).aspx
Вот мой код:
Код: Выделить всё
package javasql;
import java.sql.*;
import java.util.*;
public class Program {
private static String url = "jdbc:sqlserver://localhost\\SQLExpress;database=Northwind;integratedSecurity=true;";
//private static String userName = "sa";
//private static String password = "myPassword";
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
RunDemo();
}
public static void RunDemo() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT ProductName, Price FROM Products ORDER BY ProductName");
while(results.next()) {
System.out.println("Product Name: " + results.getNString("ProductName") + " Price: $" + results.getFloat("UnitPrice"));
}
} catch (ClassNotFoundException | SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
Код: Выделить всё
run:
com.microsoft.sqlserver.jdbc.SQLServerDriver
BUILD SUCCESSFUL (total time: 0 seconds)
РЕДАКТИРОВАТЬ:
Кстати , для строки подключения, где вы видите \\SQLExpress, я попробовал удалить ее и вместо этого использовать экземплярName=SQLExpress... но это тоже не дало никакого эффекта.
РЕДАКТИРОВАТЬ 2:
ОК, я загрузил последнюю версию драйвера JDBC для MSSQL из MS и сослался на Там 2 JAR-файла. Теперь я получаю такой вывод:
Код: Выделить всё
run:
The connection to the host localhost, named instance SQLExpress failed.
Error: "java.net.SocketTimeoutException: Receive timed out".
Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434.
For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
BUILD SUCCESSFUL (total time: 15 seconds)
РЕДАКТИРОВАТЬ 3:
Исправлены еще две проблемы. Одна из них — включение браузера SQL Server, а вторая — включение TCP/ IP для SQL Server. Спасибо @Vikdor. Теперь я получаю эту ошибку:
Код: Выделить всё
run:
The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
BUILD SUCCESSFUL (total time: 15 seconds)
РЕДАКТИРОВАНИЕ 4:
Попробовал решение по этой ссылке:
http://www.coderanch.com/t/306316/JDBC/ ... ction-host
Ошибка больше не появляется в EDIT 3. Теперь получаю еще один...
Код: Выделить всё
run:
Sep 21, 2012 11:33:16 AM com.microsoft.sqlserver.jdbc.AuthenticationJNI
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
This driver is not configured for integrated authentication. ClientConnectionId:577f359e-4774-45f3-96fb-588785911817
BUILD SUCCESSFUL (total time: 14 seconds)
РЕДАКТИРОВАТЬ 5:
Это помогло:
подключение Java к MicrosoftSQLServer 2005
Я поместите путь к каталогу в переменную среды PATH. Не сработало, поэтому я также поместил sqljdbc_auth.dll в папку JDK C:\Program Files\Java\jdk1.7.0_04\bin. Решено.
Подробнее здесь: https://stackoverflow.com/questions/125 ... ot-working
Мобильная версия