把一条记录转换成一个对象
优化后:
@Override
public Account getAccountById(Integer accountId) {
List<Account> list =JdbcUtil.query(sql_selectOne, new AccountConvertor(),accountId);
return list.isEmpty()?null:list.get(0);
}
@Override
public List<Account> getAll() {
return JdbcUtil.query(sql_select, new AccountConvertor());
}
Convertor
import java.sql.ResultSet;
import java.sql.SQLException;
public interface Convertor<T> {
public T convert(ResultSet rs) throws SQLException;
}
Accountconvertor
import java.sql.ResultSet;
import java.sql.SQLException;
public class AccountConvertor<T> implements Convertor<Account> {
@Override
public Account convert(ResultSet rs) throws SQLException {
Account a=new Account();
a.setAccountid(rs.getInt(1));
a.setName(rs.getString(2));
a.setremain(rs.getInt(3));
return a;
}
}
JdbcUtil增加的方法
public static<T>List<T>query(String sql,Convertor<T> convertor,Object...objs){
List <T>list =new ArrayList<T>();
try(Connection conn=getConnection();
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql); ){
for(int i=0;i<objs.length;i++) {
ps.setObject(i+1, objs[i]);
}
ResultSet rs=ps.executeQuery();
while(rs.next()) {
list.add(convertor.convert(rs));
}
}catch(Exception e) {
e.printStackTrace();
}
return list;
}