连接到远程mysql服务器抛出错误

时间:2012-02-07 06:49:48

标签: java mysql bluej

我正在尝试连接到远程服务器(我的学校服务器访问数据库),但我没有运气,我一直得到这个

SQL Exception:
State  : 08S01
Message: Communications link failure

Last packet sent to the server was 0 ms ago.
Error  : 0

这是我在Java中找到的代码,只是复制以查看我是否可以连接..

public void test()
 {
    try
    {
       // Load the database driver
       Class.forName( "com.mysql.jdbc.Driver" ) ;

       // Get a connection to the database
       Connection conn = DriverManager.getConnection( "jdbc:mysql://my.db.url.edu;databaseName=marco;user=USERNAME;password=PASSWORD" ) ;

       // Print all warnings
       for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
       {
          System.out.println( "SQL Warning:" ) ;
          System.out.println( "State  : " + warn.getSQLState()  ) ;
          System.out.println( "Message: " + warn.getMessage()   ) ;
          System.out.println( "Error  : " + warn.getErrorCode() ) ;
       }

       // Get a statement from the connection
       Statement stmt = conn.createStatement() ;

       // Execute the query
       ResultSet rs = stmt.executeQuery( "SELECT * FROM Test" ) ;

       // Loop through the result set
       while( rs.next() )
          System.out.println( rs.getString(1) ) ;

       // Close the result set, statement and the connection
       rs.close() ;
       stmt.close() ;
       conn.close() ;
   }
   catch( SQLException se )
   {
       System.out.println( "SQL Exception:" ) ;

       // Loop through the SQL Exceptions
       while( se != null )
       {
          System.out.println( "State  : " + se.getSQLState()  ) ;
          System.out.println( "Message: " + se.getMessage()   ) ;
          System.out.println( "Error  : " + se.getErrorCode() ) ;

          se = se.getNextException() ;
       }
   }
   catch( Exception e )
   {
      System.out.println( e ) ;
   }
 }
}

为了补充信息,我使用的是Vista。可能是什么问题?

此致

1 个答案:

答案 0 :(得分:1)

连接到数据库时,为什么会出现“链接失败”的原因有很多。

  1. 阻止与数据库连接的防火墙和/或路由器
  2. 数据库本身不允许远程连接
  3. 如果您确定案例2不适用,则必须检查您身边的事情,关闭开发机器上的防病毒/防火墙软件,如果不起作用请联系数据库管理员。