来自远程服务器的MS SQL Server 2005的Java数据库连接问题

时间:2010-08-09 11:49:11

标签: java sql-server-2005 jdbc remote-server

我正在编写一个用于连接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

我没有得到上述代码中的问题,或者我需要做一些设置 连接到远程服务器。

请给我你宝贵的建议,帮助我解决这个问题。

3 个答案:

答案 0 :(得分:2)

确保将SQL Server配置为使用TCP / IP。从SQL Server的Ne​​twork Utility应用程序启用它。还要检查SQL Server是否使用端口1433(IP地址 - IPAll - TCP端口)。

尝试使用“telnet< server_host> 1433”。如果它没有连接,您将无法建立连接。

答案 1 :(得分:1)

恕我直言“拒绝连接”表示您的应用程序服务器无法看到您的数据库服务器。

  • 检查IP地址和端口。
  • 直接从数据库服务器检查数据库连接(以避免防火墙)。
  • 检查应用程序服务器的数据库连接。

希望这会对你有所帮助

答案 2 :(得分:1)

允许您的SQL服务器正在运行的PC中的第一个连接... 转到控制面板 - > ADMIN。 TOOLS --->具有高级安全性的Windows防火墙 - > Inbounded规则 - >新规则 - >选择端口单选按钮 - > next - >输入端口3306 - >单击下一步 - - >最后给出规则名称,如conn any ... click finish