我試圖連接到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