当前位置: 首页 > 教程 > DBUtils >

DBUtils更新查询

精华
小牛编辑
84浏览
2023-03-14

以下示例将演示如何使用Update查询,在DBUtils的帮助下更新记录。 我们将更新Employees表中的记录。

语法

String updateQuery = "UPDATE employees SET age=? WHERE id=?";
int updatedRecords = queryRunner.update(conn, updateQuery, 33,104);

其中,

  • updateQuery − 更新包含占位符的查询。
  • queryRunner − QueryRunner对象更新数据库中的员工对象。

为了理解上述与DBUtils相关的概念,我们编写一个将运行更新查询的示例。创建一个示例应用程序。

  • 更新在DBUtils入门应用中创建的文件MainApp.java
  • 编译并运行应用程序,如下所述。

以下是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://localhost: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.