29 JDBC API的使用

29 JDBC API的使用

在Java中,JDBC(Java Database Connectivity)是一个用于连接和操作数据库的API。它提供了一种标准的方式来执行SQL语句、获取结果以及处理数据库事务。本文将详细介绍JDBC的使用,包括连接数据库、执行SQL查询、更新操作、处理结果集和关闭连接等内容。

1. 引入JDBC库

在使用JDBC之前,需要确保你已经引入了相应的JDBC库。在使用MySQL数据库时,可以下载MySQL Connector/J,并将其添加到项目的依赖中。如果你使用Maven,可以在pom.xml中添加以下依赖:

1
2
3
4
5
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>

2. 建立数据库连接

在与数据库交互之前,首先需要建立一个数据库连接。可以使用DriverManager类来获取数据库连接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database"; // 数据库URL
String user = "your_username"; // 数据库用户名
String password = "your_password"; // 数据库密码

try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("成功连接到数据库!");
// 进行数据库操作
connection.close(); // 记得关闭连接
} catch (SQLException e) {
System.out.println("连接数据库失败: " + e.getMessage());
}
}
}

3. 执行SQL查询

获取 Connection 对象后,可以使用 StatementPreparedStatement 来执行SQL查询。PreparedStatement 更加安全,防止SQL注入。

示例:使用PreparedStatement执行查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.sql.*;

public class JDBCQueryExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, user, password)) {
String sql = "SELECT id, name FROM users WHERE age > ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, 20); // 设置参数

ResultSet resultSet = statement.executeQuery(); // 执行查询

while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

resultSet.close(); // 关闭ResultSet
} catch (SQLException e) {
System.out.println("查询失败: " + e.getMessage());
}
}
}

4. 执行SQL更新

对于更新操作(如INSERT、UPDATE、DELETE),可以使用 executeUpdate() 方法。

示例:使用PreparedStatement执行更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.sql.*;

public class JDBCUpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, user, password)) {
String sql = "UPDATE users SET age = ? WHERE id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, 30); // 设置参数
statement.setInt(2, 1); // 设置参数

int rowsAffected = statement.executeUpdate(); // 执行更新
System.out.println("更新了 " + rowsAffected + " 行.");
} catch (SQLException e) {
System.out.println("更新失败: " + e.getMessage());
}
}
}

5. 处理事务

在复杂操作中,可能需要使用事务来确保数据的一致性。通过调用 setAutoCommit(false) 来手动控制事务。

示例:使用事务处理多个操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.sql.*;

public class JDBCTxExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, user, password)) {
connection.setAutoCommit(false); // 禁用自动提交

try {
// 执行多个操作
PreparedStatement stmt1 = connection.prepareStatement("INSERT INTO users (name, age) VALUES (?, ?)");
stmt1.setString(1, "Alice");
stmt1.setInt(2, 25);
stmt1.executeUpdate();

PreparedStatement stmt2 = connection.prepareStatement("UPDATE users SET age = ? WHERE name = ?");
stmt2.setInt(1, 26);
stmt2.setString(2, "Bob");
stmt2.executeUpdate();

connection.commit(); // 提交事务
} catch (SQLException e) {
System.out.println("发生错误,回滚事务: " + e.getMessage());
connection.rollback(); // 回滚事务
}
} catch (SQLException e) {
System.out.println("数据库连接失败: " + e.getMessage());
}
}
}

6. 关闭连接

在完成所有的数据库操作后,务必关闭 ConnectionStatementResultSet 对象,以释放数据库资源。

1
2
3
4
5
6
7
8
// 在try-with-resources语句中,连接和其他资源会自动关闭
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
// 进行数据库操作
} catch (SQLException e) {
System.out.println("错误: " + e.getMessage());
}

结论

以上是JDBC API的基本使用方法,包括如何建立连接、执行SQL查询和更新、处理结果集及事务控制。在实际应用中,可以根据需求扩展和修改这些示例代码,以实现更复杂的业务逻辑。注意在实际开发中,合理使用异常处理和资源管理是非常重要的。

29 JDBC API的使用

https://zglg.work/java-one/29/

作者

AI教程网

发布于

2024-08-08

更新于

2024-08-10

许可协议