一. 架包
slf4j-api-2.0.13.jar,slf4j-api-2.0.13.jar,mysql-connector-java-8.0.29.jar
二. 导包
三. 连接代码
import java.sql.*;
import java.util.logging.Logger;
public class DatabaseConnection {
public static final Logger LOGGER = Logger.getLogger(DatabaseConnection.class.getName());
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/huzzahs?serverTimezone=UTC";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "";
// 加载 MySQL 数据库驱动
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
LOGGER.info("数据库驱动加载成功!");
} catch (ClassNotFoundException e) {
LOGGER.severe("数据库驱动加载失败:" + e.getMessage());
}
}
public static Connection getConnection() throws SQLException {
// 建立数据库连接
return DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
}
public static void main(String[] args) throws SQLException {
System.out.println(getConnection());
}
}