2017-10-04 75 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”); } –