我正在编写一个java代码来连接MS SQL Server 2005。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
我不明白上面代码中的问题出在哪里,或者我是否需要进行一些设置 连接到远程服务器。
请给我您宝贵的建议,这可以帮助我克服这个问题。
最佳答案
确保您的 SQL Server 配置为使用 TCP/IP。从 SQL Server 的网络实用程序应用程序启用它。还要检查 SQL Server 是否正在使用端口 1433(IP 地址 - IPAll - TCP 端口)。
尝试使用“telnet
关于来自远程服务器的 MS SQL Server 2005 的 Java 数据库连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3439671/