DBUtils中BeanListHandler接口的使用
程序员文章站
2024-02-05 12:44:10
原文链接:http://www.yiidian.com/dbutils/dbutils beanlisthandler.html 是ResultSetHandler接口的实现,并负责ResultSet结果级的所有记录转换成JavaBean的List集合。此类是线程安全的。 1 BeanListHan ......
原文链接:
org.apache.commons.dbutils.beanlisthandler
是resultsethandler接口的实现,并负责resultset结果级的所有记录转换成javabean的list集合。此类是线程安全的。
1 beanlisthandler的语法
list<customer> custlist= queryrunner.query(conn, "select * from customer", resulthandler);
2 beanlisthandler的示例
2.1 编写customer实体类
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; } }
2.2 编写核心类
mainapp:
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); } } }
2.3 运行测试
欢迎关注我的公众号::一点教程。获得独家整理的学习资源和日常干货推送。
如果您对我的系列教程感兴趣,也可以关注我的网站: