使用JDBC从Java连接到SQL Server(Windows身份验证模式)

6

我需要使用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);

但是我遇到了这个错误:

    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)
...

我跟随这个答案: https://dev59.com/lGcs5IYBdhLWcg3w3HkG#12524566 我在Libraries/Compile中添加了jdbc4.jar SQL Server Browser窗口服务正在运行。
在SQL Server Network Configuration中,我选择了TCP/IP属性上的Enebled。
我将TCP地址设置为1433。
在Run,VM Options中,我输入了-Djava.library.path=my path to sqljdbc_auth.dll,并在JDK中复制了bin sqljdbc_auth.dll。
我应该怎么做?
编辑: 当在cmd中写入telnet localhost 1433时,我收到“无法连接到主机,在端口1433上”。

在jdbc 4中,您不需要使用forName() - Sotirios Delimanolis
好的,那又怎样?我还是得到了同样的错误... - Blocked
如何重新启动 SQL Server?我关闭了 SQL Server Management 再重新打开,但已经试过了。 - Blocked
如果那只是一个 UI 管理工具,那是不够的。应该有一个命令来重新启动它。或者在您的运行进程中检查并终止它,然后使用其可执行文件重新启动它。 - Sotirios Delimanolis
同时,我重新启动了计算机,现在可以工作了。我需要选择您的答案,并且如果您想要在您的答案中写入“重新启动SQL Server”的信息,那就更好了。这是答案链接:http://social.msdn.microsoft.com/Forums/en-US/sqlgetstarted/thread/78298175-1ae5-4f9a-b61d-b23d585365e3 - Blocked
显示剩余3条评论
1个回答

4
如果使用Windows身份验证,您可以这样做:

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

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

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

如果需要更多细节,请参考此处提供的简短逐步指南,了解如何从Java连接到SQL Server。希望能帮到您!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接