1、查询一条数据(针对Beauty表)
package demo07; import java.sql.Connection; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.junit.jupiter.api.Test; import utils.Beauty; import utils.JDBCUtils; public class DbutilsQueryTest { /** * BeanHandler是ResultSetHandler的实现类,用于封装表中的一条记录 * @throws Exception */ @Test public void test1(){ Connection conn = null; try { QueryRunner runner = new QueryRunner(); conn = JDBCUtils.getConnectionDruid(); String sql = "select id,name,borndate from beauty where id=?"; BeanHandler<Beauty> handler = new BeanHandler<>(Beauty.class); Beauty beauty = runner.query(conn, sql, handler, 10); System.out.println(beauty); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResourse(conn, null); } } }
2、查询多条数据(构成集合)
package demo07; import java.sql.Connection; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.junit.jupiter.api.Test; import utils.Beauty; import utils.JDBCUtils; public class DbutilsQueryTest { /* * 测试查询:查询多条记录构成的集合 * * 使用ResultSetHandler的实现类:BeanListHandler */ @Test public void test2() { Connection conn = null; try { QueryRunner runner = new QueryRunner(); conn = JDBCUtils.getConnectionDruid(); String sql = "select id,name,borndate from beauty where id<?"; BeanListHandler<Beauty> handler = new BeanListHandler<>(Beauty.class); List<Beauty> list = runner.query(conn, sql, handler, 10); list.forEach(System.out::println); } catch (Exception e) { e.printStackTrace(); } JDBCUtils.closeResourse(conn, null); } }