Java Database Connectivity (JDBC) 教程
简介
Java Database Connectivity(JDBC)是 Java 编程语言用于与各种关系型数据库进行交互的标准 API。它提供了一种统一的方式,让 Java 程序可以连接到不同的数据库系统,如 MySQL、Oracle、SQL Server 等,并执行诸如查询、插入、更新和删除等操作。本教程将详细介绍 JDBC 的基础概念、使用方法、常见实践以及最佳实践,帮助读者深入理解并高效使用 JDBC。
目录
- 基础概念
- 使用方法
- 加载驱动程序
- 建立数据库连接
- 创建 Statement 对象
- 执行 SQL 语句
- 处理结果集
- 关闭资源
- 常见实践
- 插入数据
- 查询数据
- 更新数据
- 删除数据
- 最佳实践
- 使用预编译语句
- 异常处理
- 资源管理
- 小结
- 参考资料
基础概念
JDBC 是 Java 与数据库之间的桥梁,它主要由以下几个核心组件组成: - DriverManager:负责加载数据库驱动程序,并管理与数据库的连接。 - Connection:代表与数据库的一个连接,通过它可以创建 Statement 或 PreparedStatement 对象。 - Statement:用于执行静态 SQL 语句。 - PreparedStatement:用于执行预编译的 SQL 语句,具有更高的性能和安全性。 - ResultSet:用于存储 SQL 查询的结果集。
使用方法
加载驱动程序
在使用 JDBC 之前,需要先加载相应的数据库驱动程序。以 MySQL 为例:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
建立数据库连接
使用 DriverManager.getConnection()
方法建立与数据库的连接:
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
创建 Statement 对象
通过 Connection
对象创建 Statement
对象:
Statement statement = connection.createStatement();
执行 SQL 语句
使用 Statement
对象执行 SQL 语句:
String sql = "SELECT * FROM users";
try {
ResultSet resultSet = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
处理结果集
遍历 ResultSet
对象,处理查询结果:
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
关闭资源
使用完后,需要关闭 ResultSet
、Statement
和 Connection
对象:
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
常见实践
插入数据
String sql = "INSERT INTO users (name, age) VALUES ('John', 25)";
try {
int rowsInserted = statement.executeUpdate(sql);
if (rowsInserted > 0) {
System.out.println("Data inserted successfully.");
}
} catch (SQLException e) {
e.printStackTrace();
}
查询数据
String sql = "SELECT * FROM users";
try {
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
更新数据
String sql = "UPDATE users SET age = 26 WHERE name = 'John'";
try {
int rowsUpdated = statement.executeUpdate(sql);
if (rowsUpdated > 0) {
System.out.println("Data updated successfully.");
}
} catch (SQLException e) {
e.printStackTrace();
}
删除数据
String sql = "DELETE FROM users WHERE name = 'John'";
try {
int rowsDeleted = statement.executeUpdate(sql);
if (rowsDeleted > 0) {
System.out.println("Data deleted successfully.");
}
} catch (SQLException e) {
e.printStackTrace();
}
最佳实践
使用预编译语句
预编译语句可以提高性能和安全性,防止 SQL 注入攻击:
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "John");
preparedStatement.setInt(2, 25);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Data inserted successfully.");
}
} catch (SQLException e) {
e.printStackTrace();
}
异常处理
使用 try-catch-finally
块或 try-with-resources
语句进行异常处理,确保资源的正确关闭:
try (Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, "John");
preparedStatement.setInt(2, 25);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Data inserted successfully.");
}
} catch (SQLException e) {
e.printStackTrace();
}
资源管理
使用 try-with-resources
语句自动关闭资源,避免手动关闭资源时可能出现的错误:
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
小结
本教程详细介绍了 Java Database Connectivity(JDBC)的基础概念、使用方法、常见实践以及最佳实践。通过学习,读者应该能够掌握如何使用 JDBC 连接到数据库,执行常见的 SQL 操作,并遵循最佳实践来提高代码的性能和安全性。