关于JDBC的查询(两种:根据主键查询和查询多条记录),以下代码仍有待优化:
根据主键查询:
@Override
public Account getAccountById(Integer AccountId) {
Account a=null;
try(Connection conn=JdbcUtil.getConnection();
PreparedStatement ps=conn.prepareStatement(sql_selectOne);){
ps.setInt(1,AccountId);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
a=new Account();
a.setAccountid(rs.getInt(1));
a.setName(rs.getString(2));
a.setRemain(rs.getInt(3));
}
}catch(Exception e){
e.printStackTrace();
}
return a;
}
注意:返回值类型是Account;不能是ResultSet,因为操作结束后Connection和PrepareStatement关闭了,无法使用。
查询多条记录:
String sql_select="select * from account order by accountid";
@Override
public List<Account> getAll() {
List<Account> list=new ArrayList<Account>();
try(Connection conn=JdbcUtil.getConnection();
PreparedStatement ps=conn.prepareStatement(sql_select);
ResultSet rs=ps.executeQuery()){
while(rs.next()) {
Account a=new Account();
a.setAccountid(rs.getInt(1));
a.setName(rs.getString(2));
a.setRemain(rs.getInt(3));
list.add(a);
}
}catch(Exception e) {
e.printStackTrace();
}
return list;
}
方法无参数,可将ResultSet放到try()里,Connection关闭ResultSet也会关闭;
注意:Account a =new Account();要放在while里,否则同一个Account对象被赋值多次,结果如下
正确结果如下: