我们常常将主键交给数据库去维护,例如我们在创建表的时候,让主键auto_increament。
这样一来在用户插入数据之后想获取到刚刚插入数据的ID,是没办法的,现在介绍下面两种方法获取数据库自动生成的键值。
若使用的是:Statement 代码如下
public void demo12() {
try {
Connection connection = DBUtiles.getConnection();
String sql = "insert into user(username,psw) values('hehe','haha')";
Statement stmt = connection.createStatement();
stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
// 得到生成的键值
ResultSet rs = stmt.getGeneratedKeys();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
// TODO A1uto-generated catch block
e.printStackTrace();
}
}
例子是随便写的,也没有写关闭连接之类的。关键看这里:
stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
// 得到生成的键值
ResultSet rs = stmt.getGeneratedKeys();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
在执行的时候多加入一个参数:Statement.RETURN_GENERATED_KEYS
然后就可以通过stmt来拿到刚刚生成的键值了。
下面介绍PreparedStatement与statement是差不多的:
上代码:
public void demo13() {
Connection connection;
try {
connection = DBUtiles.getConnection();
String sql = "insert into user(username,psw) values(?,?)";
PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "haha");
ps.setString(2, "hehe");
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
// ps.execute(sql);
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
重点看这里:
PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "haha");
ps.setString(2, "hehe");
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
// ps.execute(sql);
while (rs.next()) {
System.out.println(rs.getInt(1));
}