JDBC和DBUtils区别(查询时jdbc只能返回ResultSet需要po转vo,dbutils返回的BeanListHandler与BeanHandler对应集合与对象)

时间:2022-09-13 04:28:27
17:34 2013/6/7
JDBC
//添加客户
public void addNewCustomer(Customer c) throws DAOException {
Connection conn = null;
PreparedStatement pst = null;
try{
conn = JDBCUtils.getConnection();
pst = conn.prepareStatement("insert into customer values(?,?,?,?,?,?,?,?)");
//赋值
pst.setString(1, c.getCid());
pst.setString(2, c.getName());
pst.setString(3, c.getGender());
pst.setDate(4, new java.sql.Date(c.getBirthday().getTime()));
pst.setString(5,c.getCellphone());
pst.setString(6, c.getEmail());
pst.setString(7, c.getType());
pst.setString(8,c.getDescription());
//执行
pst.executeUpdate();
}catch(Exception ex){
throw new DAOException(ex);
}finally{
JDBCUtils.release(conn, pst, null);
}
}
查:
//查询所有客户
public List<Customer> findAllCustomer() throws DAOException {
List<Customer> list = new ArrayList<Customer>(); Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
conn = JDBCUtils.getConnection();
pst = conn.prepareStatement("select * from customer");
rs = pst.executeQuery();
while(rs.next()){
//取每个客户
Customer c = new Customer();
c.setCid(rs.getString("cid"));
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getString("cellphone"));
c.setEmail(rs.getString("email"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description")); //放入集合
list.add(c);
}
}catch(Exception ex){
throw new DAOException(ex);
}finally{
JDBCUtils.release(conn, pst, rs);
} return list;
}
JDBC连接池DBUtils
增:
public void create(User user){
try {
// 1 核心对象
QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
// 2 sql
String sql = "insert into user(id,username,password) values(?,?,?)";
// 3 准备数据
Object[] params = {user.getId(),user.getUsername(),user.getPassword()};
// 4 执行
runner.update(sql, params);
} catch (SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
查:
public User findByUsernameAndPassword(String username, String password) {
try {
QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "select * from user where username = ? and password = ?"; Object[] params = {username,password}; return runner.query(sql, new BeanHandler<User>(User.class) ,params);
} catch (SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
} }