資料庫操作之DBUtils
阿新 • • 發佈:2018-12-15
package com.oterman.DButils; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ArrayHandler; import org.apache.commons.dbutils.handlers.ArrayListHandler;import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.MapHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler;import org.junit.Test; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * 該程式介紹ResultSetHandler的各個實現類; * @author 大蘑菇 * */ public class RSHandlerDemo { //--7.ScalarHandler:將查詢的結果的第一行的某一列放到一個物件中;精確定位到某個值; @Test public void query7() throwsSQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); String name=(String)runner.query("select * from account",new ScalarHandler(2)); System.out.println(name); } //--6.MapListHandler:將查詢的結果的每一行存入到一個map中,鍵為列名,值為各列值;然後再將map存入list中; @Test public void query6() throws SQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); List<Map<String,Object>> map=runner.query("select * from account",new MapListHandler()); System.out.println(map); } //--5.MapHandler:將查詢的結果的第一行存入到一個map中,鍵為列名,值為各列值; @Test public void query5() throws SQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); Map<String,Object> map=runner.query("select * from account",new MapHandler()); System.out.println(map); } //--4.BeanListHandler:將查詢的結果的每一行封裝到一個javabean物件中,然後再將這些物件存入list中; @Test public void query4() throws SQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); List<Account> list=runner.query("select * from account",new BeanListHandler<Account>(Account.class)); System.out.println(list); } //--3.BeanHandler:將查詢的結果的第一行封裝到一份javabean物件中; @Test public void query3() throws SQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); Account account=runner.query("select * from account",new BeanHandler<Account>(Account.class)); System.out.println(account); } //--2.ArrayListHandler:將查詢的結果的每一行放到一個數組中,然後再將陣列放到集合中; @Test public void query2() throws SQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); List<Object[]> list=runner.query("select * from account",new ArrayListHandler()); System.out.println(list); } //--1.ArrayHandler:將查詢的結果的第一行放到一個數組中 @Test public void query1() throws SQLException{ QueryRunner runner=new QueryRunner(new ComboPooledDataSource()); Object[] array=runner.query("select * from account",new ArrayHandler()); System.out.println(array); } }