简体   繁体   English

Statement.getGeneratedKeys()方法

[英]Statement.getGeneratedKeys() method

I'm currently watching a video tutorial, and I am really confused with this code: 我目前正在观看视频教程,我对此代码感到困惑:

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

Regarding the stmt.getGeneratedKeys() method, since it returns the auto-generated key as a result of executing the Statement object, why does it need to invoke the getInt() method? 关于stmt.getGeneratedKeys()方法,由于它在执行Statement对象时返回自动生成的键,为什么需要调用getInt()方法?

Also, the cursor, by default, is pointing before the inserted row so why is the next() method invoked before the get.GeneratedKeys() ? 此外,默认情况下,游标指向插入的行之前,为什么在get.GeneratedKeys()之前调用next()方法? Shouldn't the next() method be invoked first so that the cursor will go to the first result row before getting the GeneratedKey ? 不应该首先调用next()方法,以便在获取GeneratedKey之前光标将转到第一个结果行?

Two things. 两件事情。 Some databases can return multiple generated keys per row, and they do not have to be integers, they could be a GUID string or something else. 某些数据库可以每行返回多个生成的密钥,它们不必是整数,它们可以是GUID字符串或其他内容。 Therefore, you need to call getInt(1) in the code above. 因此,您需要在上面的代码中调用getInt(1) Second, you are incorrect, a ResultSet returned by JDBC is positioned before the first row, thus the need to call next(). 其次,你是不正确的,JDBC返回的ResultSet位于第一行之前 ,因此需要调用next()。 If a ResultSet has no rows, calling next() returns false indicating there are no results. 如果ResultSet没有行,则调用next()将返回false表示没有结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM