Return 插入语句后自动递增 ID 的 int
Return int with auto incremented ID after insert statement
我正在尝试 return 使用 GetGeneratedKey 方法将刚刚创建的 table id 作为 int。但这是行不通的。
我的代码
public int saveWorkout(String titel, String beschrijving, int categorie_id, int persoon_id) throws SQLException {
int result = 0;
try (Connection con = super.getConnection()) {
String query = "INSERT INTO \"Workout\" VALUES(?,?,?,?)";
String query2 = "INSERT INTO \"Workout_Oefening\" VALUES(?,?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, titel);
pstmt.setString(2, beschrijving);
pstmt.setInt(3, persoon_id);
pstmt.setInt(4, categorie_id);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
if(keys.next()) {
result = keys.getInt(1);
System.out.println(keys.getInt(1));
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return result;
}
它总是 returns 0!如果我打印 keys.getint(1) 东西它 return 如下
org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet@8a14f70
if(keys.next()) {
keys.next(); //This is being called 2nd time.
result = keys.getInt(1);
System.out.println(keys.getInt(1));
}
问题出在您的第 2 行 keys.next();
你调用了两次,即使在if条件下,它也会遍历到下一行。
用这个替换你的代码,我认为它会正常工作
if(keys.next()) {
result = keys.getInt(1);
System.out.println(keys.getInt(1));
}
参考:https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()
忘记补充了
Statement.RETURN_GENERATED_KEYS 在我准备好的陈述之后。
我正在尝试 return 使用 GetGeneratedKey 方法将刚刚创建的 table id 作为 int。但这是行不通的。
我的代码
public int saveWorkout(String titel, String beschrijving, int categorie_id, int persoon_id) throws SQLException {
int result = 0;
try (Connection con = super.getConnection()) {
String query = "INSERT INTO \"Workout\" VALUES(?,?,?,?)";
String query2 = "INSERT INTO \"Workout_Oefening\" VALUES(?,?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, titel);
pstmt.setString(2, beschrijving);
pstmt.setInt(3, persoon_id);
pstmt.setInt(4, categorie_id);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
if(keys.next()) {
result = keys.getInt(1);
System.out.println(keys.getInt(1));
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return result;
}
它总是 returns 0!如果我打印 keys.getint(1) 东西它 return 如下
org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet@8a14f70
if(keys.next()) {
keys.next(); //This is being called 2nd time.
result = keys.getInt(1);
System.out.println(keys.getInt(1));
}
问题出在您的第 2 行 keys.next();
你调用了两次,即使在if条件下,它也会遍历到下一行。
用这个替换你的代码,我认为它会正常工作
if(keys.next()) {
result = keys.getInt(1);
System.out.println(keys.getInt(1));
}
参考:https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()
忘记补充了
Statement.RETURN_GENERATED_KEYS 在我准备好的陈述之后。