即使有 jar 文件也无法将 Java 连接到 MySQL 数据库
Cannot connect Java to MySQL database even after having jar file
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbManager {
public static Connection conn = null; // mysql
public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("jdbc:mysql://localhost:3306/testdatabase");
System.out.println("test1");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase", "root", "Password");
System.out.println("test2");
if (!conn.isClosed())
System.out.println("Successfully connected to MySQL server");
} catch (Exception e) {
System.err.println("Cannot connect to database server");
}
}
}
输出为:
jdbc:mysql://localhost:3306/testdatabase
test1
Cannot connect to database server
连接未按预期工作。我已经确认安装的 jar 和连接正在使用终端上的用户名和密码。有谁知道我做错了什么?
在代码中明确提到 serverTimezone
以解决问题。
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?serverTimezone=UTC", "root", "MyPassword");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbManager {
public static Connection conn = null; // mysql
public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("jdbc:mysql://localhost:3306/testdatabase");
System.out.println("test1");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase", "root", "Password");
System.out.println("test2");
if (!conn.isClosed())
System.out.println("Successfully connected to MySQL server");
} catch (Exception e) {
System.err.println("Cannot connect to database server");
}
}
}
输出为:
jdbc:mysql://localhost:3306/testdatabase
test1
Cannot connect to database server
连接未按预期工作。我已经确认安装的 jar 和连接正在使用终端上的用户名和密码。有谁知道我做错了什么?
在代码中明确提到 serverTimezone
以解决问题。
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?serverTimezone=UTC", "root", "MyPassword");