如何向数据库添加时同时返回ID
1个回答
2017-02-01
展开全部
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);
}
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);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询