2017-10-04 50 views
0
String url = "jdbc:mysql://localhost:3306/mysql"; 
String user = "root"; 
String pass = "root1"; 

try { 
    Class.forName("com.mysql.jdbc.Driver"); 
    Connection connection = DriverManager.getConnection(url, user, pass); 
    System.out.println("Connected to database"); 
} catch (Exception e) {   
    System.out.println(e); 
    System.out.println("Could not connect to database"); 
} 

密碼應該是 「根」。程序不會在catch塊中顯示消息並停止工作。誰能告訴我會發生什麼?MySQL的JDBC連接停止工作

[更新] 我很抱歉,我問了一個不好的問題。問題已經解決了,謝謝。這有助於正確檢查連接是否存在。

if (conn1 != null) { 
    System.out.println("Connected to the database test1"); 
} 
+0

嘗試在catch塊爲'e.printStackTrace()'打印堆棧跟蹤,還粘貼錯誤這裏。 – Nidhi257

+0

它不顯示控制檯中的任何內容,只是停在那裏。它不會進入catch塊。 –

+0

嘗試評論此行'Class.forName(「com.mysql.jdbc.Driver」);'並重新運行。讓我們看... – Nidhi257

回答

-1

有三種不同的方式連接到SQL數據庫如下圖所示代碼

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
import java.util.Properties; 

public class MySQLConnectExample { 
    public static void main(String[] args) { 

     // creates three different Connection objects 
     Connection conn1 = null; 
     Connection conn2 = null; 
     Connection conn3 = null; 

     try { 
      // connect way #1 
      String url1 = "jdbc:mysql://localhost:3306/test1"; 
      String user = "root"; 
      String password = "secret"; 

      conn1 = DriverManager.getConnection(url1, user, password); 
      if (conn1 != null) { 
       System.out.println("Connected to the database test1"); 
      } 

      // connect way #2 
      String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret"; 
      conn2 = DriverManager.getConnection(url2); 
      if (conn2 != null) { 
       System.out.println("Connected to the database test2"); 
      } 

      // connect way #3 
      String url3 = "jdbc:mysql://localhost:3306/test3"; 
      Properties info = new Properties(); 
      info.put("user", "root"); 
      info.put("password", "secret"); 

      conn3 = DriverManager.getConnection(url3, info); 
      if (conn3 != null) { 
       System.out.println("Connected to the database test3"); 
      } 
     } catch (SQLException ex) { 
      System.out.println("An error occurred. Maybe user/password is invalid"); 
      ex.printStackTrace(); 
     } 
    } 
} 
+0

感謝您的幫助。 –

+0

這是如何回答這個問題的? –

+0

檢查連接是否有幫助。如果(conn1!= null){System.out.println(「連接到數據庫test1」); } –