使用Java连接到外部mysql数据库

时间:2012-02-10 03:04:23

标签: java mysql

我正在尝试连接到外部数据库,但似乎我在设置DriverManager连接的方式上可能会出错,这是我第一次使用此驱动程序进行连接时,请指点我在正确的方向?谢谢(getConnection调用可能有问题)

Class.forName( "com.mysql.jdbc.Driver" ) ;

       // Get a connection to the database
       Connection conn = DriverManager.getConnection( "jdbc:mysql://cs.cis.can.edu;databaseName=mar200;user=utest;password=utest" ) ;

错误

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

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

2 个答案:

答案 0 :(得分:2)

而不是传递一个字符串参数,尝试分开传递每个

    getConnection(String url, String user, String password)

这是DriverManager类的指南 http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html

答案 1 :(得分:1)

您可以使用单独的用户名,密码和驱动程序,而不是在一个实例中传递参数。

Connection conn = null;

           try
           {
               String userName = "testuser";
               String password = "testpass";
               String url = "jdbc:mysql://localhost/test";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               System.err.println ("Cannot connect to database server");
           }
           finally
           {
               if (conn != null)
               {
                   try
                   {
                       conn.close ();
                       System.out.println ("Database connection terminated");
                   }
                   catch (Exception e) { /* ignore close errors */ }
               }
           }

http://www.kitebird.com/articles/jdbc.html

相关问题