我正在编写一个用于连接MS SQL Server 2005的java代码.MS SQL Server位于远程服务器Windows Server 2003上。我正在尝试以下代码,但我无法建立连接:
import java.*;
public class Connect {
private java.sql.Connection con = null;
private final String url = "jdbc:sqlserver://";
private final String serverName="xxx.xxx.xxx.xxx";
private final String portNumber = "1433";
private final String databaseName="myDb";
private final String userName ="user1";
private final String password = "xxxx";
private final String selectMethod = "cursor";
// Constructor
public Connect() {}
private String getConnectionUrl() {
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties() {
System.out.println("Perform Operations ");
}
private void closeConnection() {
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Connect myDbTest = new Connect();
// myDbTest.displayDbProperties();
}
}
但我得到以下例外情况:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source) Error Trace in getConnection() : The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect Error: No active Connection
我没有得到上述代码中的问题,或者我需要做一些设置 连接到远程服务器。
请给我你宝贵的建议,帮助我解决这个问题。
答案 0 :(得分:2)
确保将SQL Server配置为使用TCP / IP。从SQL Server的Network Utility应用程序启用它。还要检查SQL Server是否使用端口1433(IP地址 - IPAll - TCP端口)。
尝试使用“telnet< server_host> 1433”。如果它没有连接,您将无法建立连接。
答案 1 :(得分:1)
恕我直言“拒绝连接”表示您的应用程序服务器无法看到您的数据库服务器。
希望这会对你有所帮助
答案 2 :(得分:1)
允许您的SQL服务器正在运行的PC中的第一个连接... 转到控制面板 - > ADMIN。 TOOLS --->具有高级安全性的Windows防火墙 - > Inbounded规则 - >新规则 - >选择端口单选按钮 - > next - >输入端口3306 - >单击下一步 - - >最后给出规则名称,如conn any ... click finish