- Apache Commons DBUtils 教程
- DBUtils - 主页
- DBUtils - 概述
- DBUtils - 环境设置
- DBUtils - 第一个应用程序
- 基本的 CRUD 示例
- DBUtils - 创建查询
- DBUtils - 读取查询
- DBUtils - 更新查询
- DBUtils - 删除查询
- Apache Commons DBUtils 示例
- DBUtils - QueryRunner 接口
- DBUtils - AsyncQueryRunner 接口
- DBUtils - ResultSetHandler 接口
- DBUtils - BeanHandler 类
- DBUtils - BeanListHandler 类
- DBUtils - ArrayListHandler 类
- DBUtils - MapListHandler 类
- 高级 DBUtils 示例
- DBUtils - 自定义处理程序
- DBUtils - 自定义行处理器
- DBUtils - 使用 DataSource
- 有用的 DBUtils 资源
- DBUtils - 快速指南
- 有用的 DBUtils 资源
- DBUtils - 讨论
Apache Commons DBUtils - 更新查询
以下示例将演示如何使用 DBUtils 通过更新查询来更新记录。我们将在 Employees 表中更新一条记录。
语法
更新查询的语法如下所示 −
String updateQuery = "UPDATE employees SET age=? WHERE id=?"; int updatedRecords = queryRunner.update(conn, updateQuery, 33,104);
其中:
updateQuery − 具有占位符的更新查询。
queryRunner − QueryRunner 对象,将在数据库中更新员工对象。
要了解与 DBUtils 相关的前述概念,我们将编写一个运行更新查询的示例。为了编写示例,让我们创建一个示例应用程序。
| 步骤 | 描述 |
|---|---|
| 1 | 更新在 DBUtils - 第一个应用程序 章节中创建的 MainApp.java 文件。 |
| 2 | 按照以下说明编译并运行应用程序。 |
以下是 Employee.java 的内容。
public class Employee {
private int id;
private int age;
private String first;
private String last;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}
以下是MainApp.java 文件的内容。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
public class MainApp {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://:3306/emp";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
public static void main(String[] args) throws SQLException {
Connection conn = null;
QueryRunner queryRunner = new QueryRunner();
DbUtils.loadDriver(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
try {
int updatedRecords = queryRunner.update(conn,
"UPDATE employees SET age=? WHERE id=?", 33,104);
System.out.println(updatedRecords + " record(s) updated.");
} finally {
DbUtils.close(conn);
}
}
}
一旦完成创建源文件,让我们运行应用程序。如果你的应用程序一切正常,它将打印如下消息 −
1 record(s) updated.
广告