org.apache.commons.dbutils.AsyncQueryRunner 类有助于在异步支持下执行长时间运行的SQL查询,此类是线程安全的。此类支持与QueryRunner相同的方法,但它返回Callable对象,这些对象可在以后用于输出。
以下是org.apache.commons.dbutils.AsyncQueryRunner类的声明-
public class AsyncQueryRunner extends AbstractQueryRunner
步骤1 - 创建一个连接对象。
步骤2 - 使用AsyncQueryRunner对象方法进行数据库操作。
以下示例将演示如何使用AsyncQueryRunner类更新记录。无涯教程将更新员工表中的可用记录之一。
String updateQuery="UPDATE employees SET age=? WHERE id=?"; future=asyncQueryRunner.update(conn, "UPDATE employees SET age=? WHERE id=?", 33,103);
updateQuery - 更新具有占位符的查询。
asyncQueryRunner - asyncQueryRunner对象以更新数据库中的员工信息。
future - 将输出的对象。
以下是 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.AsyncQueryRunner; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class MainApp { //JDBC 驱动程序名称和数据库 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/emp"; //连接数据库凭据 static final String USER = "root"; static final String PASS = "admin"; public static void main(String[] args) throws SQLException, InterruptedException, ExecutionException, TimeoutException { Connection conn = null; AsyncQueryRunner asyncQueryRunner = new AsyncQueryRunner( Executors.newCachedThreadPool()); DbUtils.loadDriver(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); Future<Integer> future = null; try { future = asyncQueryRunner.update(conn, "UPDATE employees SET age=? WHERE id=?", 33,103); Integer updatedRecords = future.get(10, TimeUnit.SECONDS); System.out.println(updatedRecords + " record(s) updated."); } finally { DbUtils.close(conn); } } }
创建完源文件后,让无涯教程运行该应用程序。如果您的应用程序一切正常,它将打印以下消息。
1 record(s) updated.
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕