
- 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 - 使用資料來源
- DBUtils 實用資源
- DBUtils - 快速指南
- DBUtils - 實用資源
- DBUtils - 討論
Apache Commons DBUtils - 刪除查詢
以下示例將演示如何使用 DBUtils 藉助刪除查詢來刪除記錄。我們將刪除“Employees”表中的一個記錄。
語法
刪除查詢的語法如下所述 -
String deleteQuery = "DELETE FROM employees WHERE id=?"; int deletedRecords = queryRunner.delete(conn, deleteQuery, 33,104);
其中,
deleteQuery - 佔位符刪除查詢。
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 deletedRecords = queryRunner.update(conn, "DELETE from employees WHERE id=?", 104); System.out.println(deletedRecords + " record(s) deleted."); } finally { DbUtils.close(conn); } } }
建立原始檔後,讓我們執行應用程式。如果應用程式一切正常,它將列印以下訊息 -
1 record(s) deleted.
廣告