JdbcTemplate类主要用来减少daoimpl的代码量
public static int update(String sql,Object...params) {
Connection conn=null;
PreparedStatement ps=null;
try {
conn=DruidUtil.getConn();
ps=conn.prepareStatement(sql);
//设置占位符
for(int index=0;index<params.length;index++) {
ps.setObject(index+1, params[index]);
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DruidUtil.close(null, ps, conn);
}
return 0;
}
public static List<Student> query(String sql,Object...params){
List<Student> list=new ArrayList<>();
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn=DruidUtil.getConn();
ps=conn.prepareStatement(sql);
//设置占位符
for(int index=0;index<params.length;index++) {
ps.setObject(index+1, params[index]);
}
rs=ps.executeQuery();
while(rs.next()) {
Student stu=new Student();
stu.setId(rs.getLong("id"));
stu.setName(rs.getString("sname"));
stu.setAge(rs.getInt("age"));
list.add(stu);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DruidUtil.close(rs, ps, conn);
}
return list;
}
public Student get(Long id) {
List<Student> list=JdbcTemplate.query("select * from t_student where id=?", id);
if(list.size()==1) {
return list.get(0);
}
return null;
}