2012-02-10 65 views
1

我想連接到外部數據庫,但似乎我可能會犯我錯誤的方式,我把DriverManager連接,這是我第一次連接使用此司機,你能指點我正確的方向嗎?謝謝(可能是一些錯誤的的getConnection調用)使用Java連接到外部mysql數據庫

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 
+0

什麼錯誤或異常是你看到? – 2012-02-10 03:06:44

+0

我發佈了這個異常,但是你能否告訴我的代碼是否正確(連接字符串)? – user710502 2012-02-10 03:12:21

+0

選中此鏈接,它將幫助您創建正確的連接字符串。 [MySql連接字符串](http://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html) – havexz 2012-02-10 03:22:57

回答

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