工具类:
1 package com.jd.lastVersonJdbc; 2 3 4 import org.apache.commons.dbcp2.BasicDataSource; 5 import org.apache.commons.dbcp2.BasicDataSourceFactory; 6 import org.junit.Test; 7 8 import javax.sql.DataSource; 9 import java.util.Properties; 10 11 12 public class JdbcUtils { 13 14 static DataSource getMyDataSource() throws Exception{ 15 Properties prop=new Properties(); 16 prop.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")); 17 System.out.println(prop); 18 BasicDataSource ds=BasicDataSourceFactory.createDataSource(prop);//自动解析properites文件。 19 20 ds.setMaxIdle(2); 21 ds.setMaxTotal(12); 22 ds.setInitialSize(6); 23 return ds; 24 } 25 }
测试:
1 package com.jd.lastVersonJdbc; 2 3 import org.apache.commons.dbutils.QueryRunner; 4 import org.apache.commons.dbutils.handlers.MapListHandler; 5 6 7 import javax.sql.DataSource; 8 import java.util.List; 9 import java.util.Map; 10 11 public class testJdbc { 12 public static void main(String ... args)throws Exception{ 13 DataSource ds= JdbcUtils.getMyDataSource(); 14 QueryRunner qr=new QueryRunner(ds); 15 String sql="select * from system_user"; 16 MapListHandler mp=new MapListHandler(); 17 List<Map<String,Object>> rest=qr.query(sql,mp); 18 19 for(Map<String,Object> pbj:rest){ 20 System.out.println(pbj.get("username")); 21 } 22 } 23 }