在上一章节中,我们了解了JDBC的基础知识和基本用法。本章节将进一步深入,介绍如何使用JDBC进行具体的数据库操作。我们将涵盖数据库连接的管理、执行SQL查询、处理结果集、执行更新操作,以及如何使用PreparedStatement防止SQL注入攻击。通过本章节的学习,你将能够在Java应用程序中实现完整的数据库交互功能。
数据库操作概述
使用JDBC进行数据库操作通常包括以下几种常见的任务:
- 连接到数据库:通过DriverManager类获取数据库连接。
- 执行SQL查询:使用Statement或PreparedStatement对象执行SQL查询语句。
- 处理结果集:处理SQL查询的结果。
- 执行更新操作:使用Statement或PreparedStatement对象执行更新操作(INSERT、UPDATE、DELETE)。
- 事务管理:管理数据库事务,确保数据一致性。
数据库连接管理
在进行任何数据库操作之前,我们首先需要建立与数据库的连接。连接管理包括加载数据库驱动程序和通过DriverManager类获取连接。
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, username, password);
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
执行SQL查询
SQL查询操作通常是通过Statement或PreparedStatement对象来完成的。Statement对象适用于静态SQL查询,而PreparedStatement对象适用于动态SQL查询,且能够防止SQL注入攻击。
使用Statement执行SQL查询
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connection.createStatement();
String sql = "SELECT * FROM users";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
使用PreparedStatement执行SQL查询
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
String sql = "SELECT * FROM users WHERE id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
执行更新操作
更新操作包括INSERT、UPDATE和DELETE,通常也是通过Statement或PreparedStatement对象来执行。
使用Statement执行更新操作
Statement statement = null;
try {
statement = connection.createStatement();
String sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";
int rowsInserted = statement.executeUpdate(sql);
System.out.println("Rows inserted: " + rowsInserted);
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (statement != null) statement.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
使用PreparedStatement执行更新操作
PreparedStatement preparedStatement = null;
try {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "John Doe");
preparedStatement.setString(2, "john.doe@example.com");
int rowsInserted = preparedStatement.executeUpdate();
System.out.println("Rows inserted: " + rowsInserted);
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (preparedStatement != null) preparedStatement.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
事务管理
在进行复杂的数据操作时,事务管理非常重要。通过事务管理,可以确保数据操作的一致性和完整性。
try {
connection.setAutoCommit(false); // 开始事务
// 执行多个数据库操作
String insertSql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement insertStmt = connection.prepareStatement(insertSql);
insertStmt.setString(1, "Jane Doe");
insertStmt.setString(2, "jane.doe@example.com");
insertStmt.executeUpdate();
String updateSql = "UPDATE users SET email = ? WHERE name = ?";
PreparedStatement updateStmt = connection.prepareStatement(updateSql);
updateStmt.setString(1, "jane.doe@newdomain.com");
updateStmt.setString(2, "Jane Doe");
updateStmt.executeUpdate();
connection.commit(); // 提交事务
}
catch (SQLException e) {
try {
connection.rollback(); // 回滚事务
}
catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}
finally {
try {
connection.setAutoCommit(true); // 恢复自动提交模式
}
catch (SQLException e) {
e.printStackTrace();
}
}
关闭资源
为了防止资源泄漏,必须在操作完成后关闭数据库连接和其他资源。
try {
if (connection != null) connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
总结
通过本篇博客,你已经了解了如何使用JDBC进行各种数据库操作,包括连接数据库、执行SQL查询、处理结果集、执行更新操作,以及事务管理。掌握这些技能后,你可以在Java应用程序中实现复杂的数据操作,确保数据的一致性和完整性。在后续的章节中,我们将继续深入探讨JDBC的高级特性和优化技巧,帮助你在实际项目中更高效地进行数据库编程。希望你通过本篇博客能够对JDBC有一个全面的了解,并能够灵活应用于实际的开发工作中。祝你学习愉快,不断进步!