【发布时间】:2012-01-26 00:07:45
【问题描述】:
我正在尝试使用以下代码连接到本地计算机上的 SQL Server 数据库:
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.".
到目前为止,我已经进入 Configuration Mgr 并激活并启用了 TCP/IP。
我还进入并在“属性”>“IP 地址”选项卡下将每个 IP 地址设置为打开并处于活动状态。
几个潜在的问题。
当我查看 SQL Server Browser 的状态时,它是“已停止”。我不确定这是否是一个问题,如果是,如何解决。
我正在使用sqljdbc4.jar 文件并将其放在项目的引用库部分中。
如果您有任何建议,请告诉我。
编辑:
我使用的是 Windows 7 机器。
更新:
>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 Browser 不需要运行。但是对于 JDBC 连接,如果您关闭 SQL Server 动态端口并通过 SQL Server 配置应用程序强制所有网络接口使用端口 1433,则会更容易。
-
我需要重新启动服务器并打开错误日志记录。重启服务器的窗口隐藏在其他一些窗口后面,没有看到。
标签: java sql-server sql-server-2008 jdbc