原文連接:http://www.yiidian.com/dbutil...html
org.apache.commons.dbutils.BeanListHandler
是ResultSetHandler接口的實現,並負責ResultSet結果級的全部記錄轉換成JavaBean的List集合。此類是線程安全的。java
List<Customer> custList= queryRunner.query(conn, "SELECT * FROM customer", resultHandler);
package com.yiidian.domain; /** * 一點教程網 - http://www.yiidian.com */ public class Customer { private Integer id; private String name; private String gender; private String telephone; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
MainApp:mysql
package com.yiidian.dbutils; import com.yiidian.domain.Customer; import org.apache.commons.dbutils.AsyncQueryRunner; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.*; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * 一點教程網 - http://www.yiidian.com */ public class MainApp { // 驅動程序 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; // URL鏈接 static final String DB_URL = "jdbc:mysql://localhost:3306/test"; //數據庫信息 static final String USER = "root"; static final String PASS = "root"; 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); ResultSetHandler<List<Customer>> resultHandler = new BeanListHandler<Customer>(Customer.class); try { List<Customer> custList = queryRunner.query(conn, "SELECT * FROM customer", resultHandler); for(Customer customer: custList ) { System.out.print("編號: " + customer.getId()); System.out.print(", 用戶名: " + customer.getName()); System.out.print(", 性別: " + customer.getGender()); System.out.print(", 聯繫電話: " + customer.getTelephone()); System.out.println(", 住址: " + customer.getAddress()); } } finally { DbUtils.close(conn); } } }
歡迎關注個人公衆號::一點教程。得到獨家整理的學習資源和平常乾貨推送。
若是您對個人系列教程感興趣,也能夠關注個人網站: yiidian.com