一、环境准备
1.1 依赖管理(Maven)
在项目的 pom.xml 中添加 MySQL 驱动依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
二、基础连接实现
public class MySQLConnector {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("连接成功!");
// 执行数据库操作...
} catch (SQLException e) {
System.err.println("连接失败:" + e.getMessage());
}
}
}
三、高级连接管理
3.1 连接池配置
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUser("root");
dataSource.setPassword("password");
dataSource.setMinPoolSize(5);
dataSource.setMaxPoolSize(20);
dataSource.setAcquireIncrement(5);
3.2 异常处理最佳实践
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
// 执行操作
} catch (SQLTransientConnectionException e) {
// 处理临时连接异常(重试逻辑)
} catch (SQLNonTransientException e) {
// 处理永久性错误(如语法错误)
} finally {
// 自动关闭资源(try-with-resources)
}
四、 完整示例
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private static final String USER = "root";
private static final String PASSWORD = "password";
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("驱动加载失败", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
// 记录日志
}
}
}