在插入语句后返回带有自动递增ID的int

时间:2018-06-23 13:37:12

标签: java jdbc key prepared-statement

我正在尝试使用GetGeneratedKey方法将刚创建的表ID作为一个整数返回。但这不起作用。

我的代码

    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;
}

它总是返回0!如果我打印keys.getint(1),它会返回以下内容

org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet@8a14f70

2 个答案:

答案 0 :(得分:0)

if(keys.next()) {
            keys.next(); //This is being called 2nd time.
            result = keys.getInt(1);
            System.out.println(keys.getInt(1));
        }

问题出在第二行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()

答案 1 :(得分:0)

我忘记添加

Statement.RETURN_GENERATED_KEYS我准备的语句后。