MySQL JDBC连接停止工作
密码应为“root”。程序不会在catch块中显示消息,并停止工作。谁能告诉我发生了什么事 [更新] 对不起,我问了一个不好的问题。问题已经解决了,谢谢。这有助于正确检查连接是否存在MySQL JDBC连接停止工作,mysql,jdbc,Mysql,Jdbc,密码应为“root”。程序不会在catch块中显示消息,并停止工作。谁能告诉我发生了什么事 [更新] 对不起,我问了一个不好的问题。问题已经解决了,谢谢。这有助于正确检查连接是否存在 String url = "jdbc:mysql://localhost:3306/mysql"; String user = "root"; String pass = "root1"; try { Class.forName("com.mysql.jdbc.Driver"); Connecti
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");
}
有三种不同的方式连接到SQL数据库,如下代码所示
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
尝试将catch块中的stackTrace打印为
e.printStackTrace()
,并将该错误粘贴到此处。它不会在控制台中显示任何内容,只需在此处停止即可。它没有进入catch块。试着注释这一行Class.forName(“com.mysql.jdbc.Driver”)代码>并重新运行。让我们看看…尝试使用Debugger这如何回答问题?检查连接是否存在有帮助。如果(conn1!=null){System.out.println(“连接到数据库test1”);}
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();
}
}
}