结果集常用类实现
List为空的类返回值是[]、没有List的类为空返回值是null
sql = "select * from category";
// ArrayHandle
// 只获取首行数据
Arrays.toString(queryRunner.query(sql, new ArrayHandler()));
// ArrayListHander
// 获取多行数据
List<Object[]> query = queryRunner.query(sql, new ArrayListHandler());
for(Object[] objs: query){
System.out.println("category_id:" + objs[0]);
System.out.println("category_name:" + objs[1]);
}
// BeanHandler
// 获取一个对象
Category query = queryRunner.query(sql, new BeanHandler<>(Category.class));
System.out.println(query.getCategory_id());
System.out.println(query.getCategory_name());
// BeanListHandler
// 获取对象数组
List<Category> query = queryRunner.query(sql, new BeanListHandler<>(Category.class));
for(Category cat: query){
System.out.println(cat.getCategory_id() +"——"+ cat.getCategory_name());
}
// MapHandler
// 获取一个map字典
Map<String, Object> query = queryRunner.query(sql, new MapHandler());
System.out.println(query.getOrDefault("category_id", "0"));
System.out.println(query.getOrDefault("category_name", "null"));
// MapListHandler
List<Map<String, Object>> query = queryRunner.query(sql, new MapListHandler());
for(Map map: query){
System.out.println(map.getOrDefault("category_id", "0") +"——"+
map.getOrDefault("category_name", "null"));
}
数据库操作函数
queryRunner.update(sql);
int update("insert into table value(...)"); // 增
int update("delete from table where id=1"); // 删
int update("update table set id=2 where id=1");//改
queryRunner.query(sql, rsh);
ResultSetHandler query("select * from table", new ResultSetHandler());
基本用法
初始化线程池
public class PoolUtils {
private static DataSource dataSource = null;
static {
//完成连接池的初始化
InputStream ips = PoolUtils.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties();
try {
properties.load(ips);
} catch (IOException e) {
e.printStackTrace();
}
try {
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 对外提供连接!
*/
public static DataSource getDataSource() {
return dataSource;
}
/**
* 对外提供获取连接的方法!
*/
public static Connection getConnection() throws SQLException {
//使用连接池获取连接返回
return dataSource.getConnection();
}
}
public class test{
private static QueryRunner queryRunner = new QueryRunner(PoolUtils.getDataSource());
private static String sql = "select * from category";
public static void main(String[] args) throw SQLException {
System.out.println(Arrays.toString(queryRunner.query(sql, new ArrayHandler())));
}
}