使用jdbc从java连接到sql server(Windows身份验证模式)

Blo*_*ked 5 java netbeans jdbc sql-server-2008 netbeans-7

我需要使用jdbc 4.0从java连接到Sql Server 2008 .我有一个非常简单的代码:

 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
 String connectionUrl = "jdbc:sqlserver://localhost;" +
    "integratedSecurity=true;";
 Connection con = DriverManager.getConnection(connectionUrl);
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

    Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: 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.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
...
Run Code Online (Sandbox Code Playgroud)

我按照这个答案:https://stackoverflow.com/a/12524566/1554397

我在Libraries/Compile中添加了jdbc4.jar

SQL Server Browser Windows服务正在运行.

在SQL Server网络配置中,我选择了Enebled on TCP/IP属性.

我将TCP地址设置为1433.

在运行,VM选项我把-Djava.library.path =我的路径sqljdbc_auth.dll并在JDk中复制,在bin sqljdbc_auth.dll中.

我该怎么办?

编辑: 当写入cmd telnet localhost 1433时,我得到'无法打开与主机的连接,在端口1433'

Thu*_*usi 4

如果使用 Window 身份验证,您可以执行以下操作:

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
Run Code Online (Sandbox Code Playgroud)

然后将 sqljdbc_auth.dll 的路径添加为 VM 参数(构建路径中需要 sqljdbc4.jar)。

如果您需要更多详细信息,请查看此处的简短分步指南,了解如何从 Java 连接到 SQL Server。希望能帮助到你!