从刚刚插入的自增型主键表中获取主键
user表有如下列(userid,regtime,flag,loginname,powerstr,password,usertype,lasttime,secondpwd)
数据库是sqlserver 2000。
代码如下:
Connection con = Conn.getConn();
PreparedStatement ptmt = null;
ResultSet rs = null;
int userid = -1; //获取s_user中插入数据的自增型主键用户编号userid
String sql ="insert into user(regtime,flag,loginname,powerstr,password,usertype,lasttime,secondpwd) values(?,?,?,?,?,?,?,?)";
try{
ptmt = con.prepareStatement(sql);
ptmt.setString(1, regtime);
ptmt.setInt(2, flag);
ptmt.setString(3, loginname);
ptmt.setString(4, powerstr);
ptmt.setString(5, password);
ptmt.setInt(6, userType);
ptmt.setString(7, lasttime);
ptmt.setString(8, secondpwd);
if(ptmt.executeUpdate() > 0){
ptmt = con.prepareStatement("Select @@identity as userid");
//ptmt = con.prepareStatement(sql);
rs = ptmt.executeQuery();
System.out.println("插入s_user表成功!!");
if(rs.next()){
userid = rs.getInt("userid");
System.out.println(userid);
};
}
}catch(
SQLException e){
e.printStackTrace();
}finally{
try{
ptmt.close();
con.close();
}catch(SQLException e){
e.printStackTrace();
}
}
结果是那个userid输出是0,这应该是有问题的。小弟菜鸟,望各位大侠帮助。
------解决方案--------------------
Select @@identity as userid
这个是不可靠的,建议不使用。
可以这样
Java code
Connection conn = getConnection();
String sql = "insert into useres (name) values ('101')";
Statement smt = conn.createStatement();
smt.executeUpdate(sql);
ResultSet rs = smt.getGeneratedKeys();
int lastid = 0;
if(rs.next()){
lastid = System.out.println(rs.getInt(1));
}
conn.close();