如何使用 Java 删除数据库记录179


在 Java 中,使用 JDBC(Java 数据库连接)来与数据库进行交互。JDBC 提供了标准的 API,允许 Java 程序访问各种关系型数据库,例如 MySQL、Oracle 和 PostgreSQL。

要删除数据库记录,可以使用 JDBC 中的 Statement 或 PreparedStatement 接口。这两个接口都提供了 executeUpdate() 方法,该方法用于执行更新操作(例如删除、插入或更新)。

使用 Statement

以下代码段演示了如何使用 Statement 删除数据库记录:
import ;
import ;
import ;
import ;
public class DeleteRecordWithStatement {
public static void main(String[] args) {
// JDBC 驱动名称和数据库 URL
String JDBC_DRIVER = "";
String DB_URL = "jdbc:mysql://localhost:3306/databaseName";
// 数据库用户名和密码
String USER = "root";
String PASS = "password";
Connection connection = null;
Statement statement = null;
try {
// 注册 JDBC 驱动
(JDBC_DRIVER);
// 打开与数据库的连接
connection = (DB_URL, USER, PASS);
// 创建一个 Statement 对象
statement = ();
// 执行 SQL 删除查询
String sql = "DELETE FROM table_name WHERE id = 1";
int rowCount = (sql);
// 打印受影响的行数
("Records deleted: " + rowCount);
} catch (ClassNotFoundException | SQLException e) {
();
} finally {
// 关闭资源
try {
if (statement != null) {
();
}
if (connection != null) {
();
}
} catch (SQLException se) {
();
}
}
}
}

使用 PreparedStatement

PreparedStatement 接口提供了比 Statement 更安全的方法来执行更新操作。它允许您指定参数,从而可以防止 SQL 注入攻击。
import ;
import ;
import ;
import ;
public class DeleteRecordWithPreparedStatement {
public static void main(String[] args) {
// JDBC 驱动名称和数据库 URL
String JDBC_DRIVER = "";
String DB_URL = "jdbc:mysql://localhost:3306/databaseName";
// 数据库用户名和密码
String USER = "root";
String PASS = "password";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 注册 JDBC 驱动
(JDBC_DRIVER);
// 打开与数据库的连接
connection = (DB_URL, USER, PASS);
// 创建一个 PreparedStatement 对象
String sql = "DELETE FROM table_name WHERE id = ?";
preparedStatement = (sql);
// 设置参数
(1, 1);
// 执行 SQL 删除查询
int rowCount = ();
// 打印受影响的行数
("Records deleted: " + rowCount);
} catch (ClassNotFoundException | SQLException e) {
();
} finally {
// 关闭资源
try {
if (preparedStatement != null) {
();
}
if (connection != null) {
();
}
} catch (SQLException se) {
();
}
}
}
}


使用 Java 中的 JDBC,可以使用 Statement 或 PreparedStatement 接口轻松地删除数据库记录。Statement 接口提供了一种简单的方法来执行更新操作,而 PreparedStatement 接口提供了更安全的方法,可以防止 SQL 注入攻击。

2024-11-08


上一篇:Java 特殊字符转义续列表

下一篇:Java 删除代码的全面指南