标签:
向父类中添加查找方法:
1 package com.xxyh.jdbc.dao.refactor; 2 import java.sql.Connection; 3 import java.sql.PreparedStatement; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import com.xxyh.jdbc.JdbcUtils; 7 import com.xxyh.jdbc.dao.DaoException; 8 public abstract class AbstractDao { 9 10 public Object find(String sql, Object[] args) { 11 Connection conn = null; 12 PreparedStatement ps = null; 13 ResultSet rs = null; 14 try { 15 conn = JdbcUtils.getConnection(); 16 ps = conn.prepareStatement(sql); 17 for (int i = 0;i < args.length; i++) 18 ps.setObject(i+1, args[i]); 19 rs = ps.executeQuery(); 20 Object obj = null; 21 while(rs.next()) { 22 obj = rowMapper(rs); 23 } 24 return obj; 25 } catch (SQLException e) { 26 throw new DaoException(e.getMessage(), e); 27 } finally { 28 JdbcUtils.close(rs, ps, conn); 29 } 30 } 31 32 abstract protected Object rowMapper(ResultSet rs) throws SQLException; 33 34 /** 35 * 动态更新 36 * @param sql 更新语句 37 * @param args 需要传入的参数 38 * @return 返回结果条数 39 */ 40 public int update(String sql, Object[] args) { 41 Connection conn = null; 42 PreparedStatement ps = null; 43 ResultSet rs = null; 44 try { 45 conn = JdbcUtils.getConnection(); 46 ps = conn.prepareStatement(sql); 47 48 for (int i = 0; i < args.length; i++) 49 ps.setObject(i+1, args[i]); 50 51 return ps.executeUpdate(); 52 } catch (SQLException e) { 53 throw new DaoException(e.getMessage(),e); 54 } finally { 55 JdbcUtils.close(rs, ps, conn); 56 } 57 } 58 }
完善实现类:
1 package com.xxyh.jdbc.dao.refactor; 2 import java.sql.ResultSet; 3 import java.sql.SQLException; 4 import com.xxyh.jdbc.domain.User; 5 public class UserDaoImpl extends AbstractDao{ 6 7 public User findUser(String name) { 8 String sql = "select id, name, money, birthday from user where name=?"; 9 Object[] args = new Object[] {name}; 10 Object user = super.find(sql, args); 11 return (User)user; 12 } 13 14 public void delete(User user) { 15 String sql = "delete from user where id=?"; 16 Object[] args = new Object[] {user.getId()}; 17 super.update(sql, args); 18 } 19 20 public void update(User user) { 21 String sql = "udpate user set name=?,birthday=?,money=? where id=?"; 22 Object[] args = new Object[] {user.getName(),user.getBirthday(), 23 user.getMoney(),user.getId()}; 24 super.update(sql, args); 25 } 26 @Override 27 protected User rowMapper(ResultSet rs) throws SQLException { 28 User user = new User(); 29 user.setId(rs.getInt("id")); 30 user.setName(rs.getString("name")); 31 user.setMoney(rs.getFloat("money")); 32 user.setBirthday(rs.getDate("birthday")); 33 return user; 34 } 35 }
标签:
原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4394785.html