标签:des style class blog c code
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); } } }
JDBC和DBUtils的模板代码,布布扣,bubuko.com
标签:des style class blog c code
原文地址:http://www.cnblogs.com/YingYue/p/3741938.html