我试图连接到SQL Server数据库使用下面的代码我的本地机器上:的Java/SQL Server 2008 R2的快速连接问题
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
import java.sql.*;
public class JDBConn {
//public class connectURL {
public static void main(String[] args) {
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
// Create a variable for the connection string.
//String connectionUrl = "jdbc:sqlserver://localhost;database=optRes1;integratedSecurity=true;";
//con = DriverManager.getConnection(connectionUrl);
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost";
con = DriverManager.getConnection(connectionUrl);
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT * FROM some_table_name");
while (r.next()) {
System.out.println(r.getString(1));
}
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * from [optRes1].[dbo].[unEmpDat]";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
我收到以下消息时,我尝试连接(我使用Eclipse作为IDE):
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, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
到目前为止,我已进入配置管理器并激活并启用了TCP/IP。
我也走了,并设置每个IP地址,并在属性> IP地址选项卡下激活。
一些潜在的问题。
当我查看SQL Server浏览器的状态时,它被“停止”。我不确定这是否是一个问题,以及如何解决问题。
我正在使用sqljdbc4.jar
文件并将其放在项目的引用库部分。
如果您有任何建议,请告诉我。
编辑:
我正在使用Windows 7框。
UPDATE:
>java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) 64-Bit Server VM (build 14.0-b16, mixed mode)
启动服务器。 –
SQL Server **浏览器**不需要运行。但使用JDBC连接时,关闭SQL Server动态端口并强制所有网络接口通过SQL Server配置应用程序使用端口1433会更容易。 –
我需要重新启动服务器并打开错误日志记录。重新启动服务器的窗口隐藏在其他一些窗口的后面,没有看到它。 – screechOwl