QurryRunner qr = new QuerryRunner(DruidUtils.getdataSource())
//多个结果,返回list集合,每条记录由map进行封装
List<Map<String,Object> queryList = qr.query(sql, new MapListHandler(), params);
//一条结果,返回Map,
Map<String,Object> queryMap = qr.query(sql, new MapHandler(), params);
//其他增删改,均可直接调用update,返回0或者-1,如果修改,删除该条记录不存在时,同样返回0,表示成功
int result = qr.update(sql, params);
有部分人喜欢结果集以javabean的方式存储,个人感觉javabean方式比较笨重,还是比较喜欢直接以list或者map的方式来进行存储数据,下面列出所有支持的结果集
结果集ResultSetHandler接口(org.apache.commons.dbutils.ResultSethandler)执行处理一个结果集对象,将数据转变并处理为任何一种形式,供其他应用使用。实现类如下:
ArrayHandler:把结果集中的第一行数据转成对象数组。
ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。
BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
ColumnListHandler:将结果集中某一列的数据存放到List中。
KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里(List<Map>),再把这些map再存到一个map里,其key为指定的列。
ScalarHandler:将结果集第一行的某一列放到某个对象中。
public class DruidUtils {
private static DruidDataSource ds;
static {
try {
InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("application.properties");
Properties properties = new Properties();
properties.load(is);
ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource() {
if (ds != null) {
return ds;
}
return null;
}
}
public class C3P0Utils {
//1. 在成员变量位置创建一个静态的ComboPooledDtatSource 对象
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//2. 在静态代码块中使用ComboPooledDtatSource 对象 setxxxx方法 设置数据库连接
static {
InputStream in = C3P0Utils.class.getClassLoader().getResourceAsStream("/conf/database.atmp.properties");
Properties properties = new Properties();
try {
properties.load(in);
//设置注册驱动程序
dataSource.setDriverClass(properties.getProperty("driverClass"));
//设置URL
dataSource.setJdbcUrl(properties.getProperty("url"));
//设置数据库用户名
dataSource.setUser(properties.getProperty("username"));
//设置数据库密码
dataSource.setPassword(properties.getProperty("password"));
} catch (PropertyVetoException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ComboPooledDataSource getdataSource() {
return dataSource;
}
//3. 定义一个静态方法 ComboPooledDtatSource 对象中获得数据库连接 Coonection
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("数据库连接失败");
}
}
//4. 释放资源(归还);
public static void close(ResultSet rs, Statement stat, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();//不是关 是归还
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}