67,513
社区成员
发帖
与我相关
我的任务
分享
public Stu load(String id) {
QR<?> qr = new QR<>(C3P0.getDataSource());
String sql = "select * from stu where id=?";
Object[] params = { id };
RsHandler<Stu> rh = new RsHandler<Stu>() {
public Stu handler(ResultSet result) {
if (!result.next())
return null;
Stu stu = new Stu();
stu.setId(result.getString("id"));
stu.setName(result.getString("name"));
stu.setSex(result.getString("sex"));
return stu;
}
};
return (Stu) qr.query(sql, rh, params);
}
public interface RsHandler<T> {
public T handler(ResultSet result) throws RuntimeException;
}
public T query(String sql, RsHandler<T> rh, Object... params) {
Connection con = null;
PreparedStatement psmt = null;
ResultSet result = null;
try {
con = dataSource.getConnection();// 通过连接池得到链接对象
psmt = con.prepareStatement(sql);// 使用sql创建psmt
initParams(psmt, params);// 设置参数
result = psmt.executeQuery();// 执行
return rh.handler(result);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (psmt != null)
psmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
}
}
}