rs.open sql,conn,1,2
rs.addnew
....
rs.update()
id=rs("id")
rs.close
...
记录集update以后,指针还是停留在最后一个记录..在close方法之前使用
public void save(Person p) throws SQLException {String sql = "insert into person (name,pwd,sex,age,email,loves) values(?,?,?,?,?,?)"
Connection conn = DbUtil.getConnection()
PreparedStatement pst = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS)
pst.setString(1, p.getName())
pst.setString(2, p.getPwd())
pst.setString(3, p.getSex())
pst.setInt(4, p.getAge())
pst.setString(5, p.getEmail())
StringBuffer loves = new StringBuffer("")
//将爱好信息拼成字符串
for(String s:p.getLoves()){
loves.append(s)
loves.append(",")
}
//如果用户没选择爱好,则写入""
if(loves.length()>0){
loves.substring(0, loves.length()-1)
pst.setString(6, loves.toString())
}else{
pst.setString(6,"")
}
pst.executeUpdate()
ResultSet rs = pst.getGeneratedKeys()
rs.next()
int id = rs.getInt(1)
p.setId(id)
DbUtil.closeConnection(conn)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)