我目前正在观看一个视频教程,我真的对这段代码感到困惑:
public static boolean insert(Member mbr) throws Exception {
String SQL = "INSERT INTO test (first_name, last_name) " +
"VALUES (?, ?)";
ResultSet keys = null;
try (
Connection con = DBUtil.getConnection(DBType.MYSQL);
PreparedStatement stmt = con.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
) {
stmt.setString(1, mbr.getFname());
stmt.setString(2, mbr.getLname());
int affected = stmt.executeUpdate();
if (affected == 1) {
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
mbr.setMemberid(newKey);
} else {
System.err.println("No rows affected");
return false;
}
} finally {
if (keys != null) keys.close();
}
return true;
}
关于stmt.getGeneratedKeys()
方法,既然是执行Statement对象返回自动生成的key,那为什么还要调用getInt()
方法呢?
此外,默认情况下,光标指向插入的行之前,那么为什么next()
在get.GeneratedKeys()
? 不应该next()
先调用该方法,以便光标在获取GeneratedKey
?