在表中使用代码插入记录,其中一个字段是自动递增的(id)。如何才能找到我刚才插入的记录中的自动递增字段(id)的值?
PreparedStatement ps = null;
Connection con = null;
ResultSet rs = null;
int rows = 0;
try {
String SQL_DRV = "org.hsqldb.jdbcDriver";
String SQL_URL = "jdbc:hsqldb:hsql://localhost/localDB";
Class.forName(SQL_DRV);
con = DriverManager.getConnection(SQL_URL, "sa", "");
ps = con.prepareStatement(
"insert into infousuarios (nombre, apellidos, email) " +
"values (?, ?, ?)");
ps.setString(1, name);
ps.setString(2, surnames);
ps.setString(3, login+"@micorreo.com");
rows = ps.executeUpdate();
// How I can know the value of autoincrement field (id) of the record just enter??发布于 2014-12-03 12:13:35
使用getGeneratedKeys()
ps = con.prepareStatement(
"insert into infousuarios (nombre, apellidos, email) " +
"values (?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setString(2, surnames);
ps.setString(3, login+"@micorreo.com");
rows = ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
long id = -1;
if (keys.next()) {
id = rs.getLong(1);
}注意对prepareStatement传递PreparedStatement.RETURN_GENERATED_KEYS的调用和对ps.getGeneratedKeys()的调用
发布于 2014-12-03 12:07:42
insert_id可以检索最后插入的id $id=$mysqli->insert_id;
https://stackoverflow.com/questions/27271296
复制相似问题