java如何连接mysql数据库
连接 MySQL 数据库的步骤
添加 MySQL 驱动依赖
在项目中引入 MySQL 的 JDBC 驱动。如果使用 Maven,可以在 pom.xml 中添加以下依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
加载并注册 JDBC 驱动
使用 Class.forName() 方法加载 MySQL 驱动:
Class.forName("com.mysql.cj.jdbc.Driver");
建立数据库连接
通过 DriverManager.getConnection() 方法建立连接,需提供数据库 URL、用户名和密码:

String url = "jdbc:mysql://localhost:3306/database_name?useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
执行 SQL 查询
使用 Statement 或 PreparedStatement 执行 SQL 查询:
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");
while (resultSet.next()) {
String columnValue = resultSet.getString("column_name");
System.out.println(columnValue);
}
关闭连接
完成操作后,关闭所有资源以释放数据库连接:

resultSet.close();
statement.close();
connection.close();
使用 PreparedStatement 防止 SQL 注入
推荐使用 PreparedStatement 执行参数化查询:
String sql = "INSERT INTO users (username, email) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "user1");
preparedStatement.setString(2, "user1@example.com");
preparedStatement.executeUpdate();
处理异常
使用 try-with-resources 自动管理资源并捕获异常:
try (Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, "value");
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
连接池配置(可选)
对于生产环境,建议使用连接池(如 HikariCP)管理数据库连接:
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/database_name");
config.setUsername("root");
config.setPassword("password");
HikariDataSource dataSource = new HikariDataSource(config);
Connection connection = dataSource.getConnection();






