- 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.
廣告