問題描述:最簡單的數據庫連接報錯,到主機 的 TCP/IP 連接失敗。(win 7 操作系統)
錯誤信息:
com.microsoft.sqlserver.jdbc.SQLServerException: 到主機 的 TCP/IP 連接失敗。 java.net.ConnectException: Connection refused: connect
package sqlconnect;
import java.sql.*;
public class sqlconnect {
public static void main(String[] args) {
String user = "zcj";
String password = "123";
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=lol";
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String tableName = "lol";
String sqlstr;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName(driver);
con = DriverManager.getConnection(url,user,password);
stmt = con.createStatement();
sqlstr = "insert into " + tableName + " values('333','333')";
stmt.executeUpdate(sqlstr);
sqlstr = "select * from " + tableName;
rs = stmt.executeQuery(sqlstr);
ResultSetMetaData rsmd = rs.getMetaData();
int j = 0;
j = rsmd.getColumnCount();
for(int k=0;k<j;j++){
System.out.print(rsmd.getColumnName(k+1));
System.out.print("/t");
}
System.out.println();
while(rs.next()){
for(int i=0;i<j;i++){
System.out.print(rs.getString(i+1));
System.out.print("/t");
}
System.out.println();
}
}
catch(ClassNotFoundException e1){
System.out.println("數據庫驅動不存在");
System.out.println(e1.toString());
}
catch(SQLException e2){
System.out.println("數據庫存在異常");
System.out.println(e2.toString());
}
finally{
try{
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(con != null)
con.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
}
}
解決方式:
安裝SQL Server 2008后。在目錄下找到SQL Server Configuration Manager這個工具,然后在左邊的目錄中找到SQL Server 2008網絡配置下的MSSQLSERVER,點擊后右側列出了所有協議,找到TCP/IP,發現是禁用狀態,啟用后再重啟MSSQLSERVER服務即可(此步驟必須!),此項可在該工具下的SQL Server 2008服務中找到,或在windows服務中找到。
可能的其他解決方式:
網上有許多答案是TCP端口不是1433,查看真實的端口並在代碼中修改即可。 可在SQL Server 2008網絡配置下的MSSQLSERVER,點擊后右側列出了所有協議,找到TCP/IP,雙擊,找到IP地址,里面有IP地址和端口號修改。
