首先假设有一个连接池 comboPooledDataSource
Class Dbutils
{ private DataSource dataSoure;
public Dbutils(DataSource dataSource)
{
this.dataSource=dataSource;
}
private void InitParams(PreparedStatement preparedStatement,Object[] params) throws SQLException
{
for(int i=0;i<params.length;i++)
{
preparedStatement.setObject(i+1, params[i]);
}
}
public int update(String sql,Object[] params)
{
Connection con = null;
PreparedStatement pre = null;
try{
con=dataSource.getConnection();
pre=con.preparedStatement();
InitParams(pre,params);
return preparedStatement.executeUpdate();
}
catch(Exception e) {
// TODO: handle exception
}
finally
{
try {
if(preparedStatement!=null)preparedStatement.close();
if(connection!=null) connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return -1;
}
public <T> T querry(String sql,RsHandler<T> rh,Object[] params)
{
Connection con = null;
PreparedStatement pre = null;
ResultSet rs=null;
try{
con=dataSource.getConnection();
pre=con.preparedStatement();
InitParams(pre,params);
rs=pre.executeQuery();
if(rs.next()) return rh.handler(rs);
}
catch(Exception e) {
// TODO: handle exception
}
finally
{
try {
if(rs!=null) rs.closer();
if(preparedStatement!=null)preparedStatement.close();
if(connection!=null) connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
interface RsHandler<T>
{
public T Handle(ResultSet resultSet) throws SQLException;
}
}
/*
* 调用query方法
*/
public void fun1() throws SQLException
{
Dbutils dbutils=new Dbutils(comboPooledDataSource);
String sql="select * from stu where sid=?";
Object[] params={1002};
RsHandler<Stu> rh = new RsHandler<Stu>(){
public Stu Handle(ResultSet resultSet) throws SQLException
{
Stu stu = new Stu();
//从resultSet里获取值
..............
return stu;
};
Stu stu = dbutils.querry(sql,rh,params)
System.out.println(stu);
}
在真正的dbutils其实有更简单的实现,就是调用BeanHandler这个实现类
public void fun2() throws SQLException
{
QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
String sql="select * from stu where sid = ?";
Object[] param={1002};
Stu stu=queryRunner.query(sql, new BeanHandler<Stu>(Stu.class), param);
System.out.println(stu);
}