简体   繁体   English

getGeneratedKeys() 方法 - 它是如何工作的?

[英]getGeneratedKeys() method - How does it work?

I've got a method, which saves an user to my database:我有一个方法,可以将用户保存到我的数据库中:

public void saveToDB(Connection conn) throws SQLException {
        if(this.id == 0) {
            String sql = "INSERT INTO Users(username, email, password) VALUES (?, ?, ?)";
            String generatedColumns[] = { "ID" };
            PreparedStatement prepStat = conn.prepareStatement(sql, generatedColumns);
            prepStat.setString(1, this.username);
            prepStat.setString(2, this.email);
            prepStat.setString(3, this.password);
            prepStat.executeUpdate();
            ResultSet rs = prepStat.getGeneratedKeys();          //those 3 lines
            if (rs.next()) {
                this.id = rs.getInt(1);
            }
        }
    }

So, that's how I understand it.所以,这就是我的理解。

conn.prepareStatement() has returned the ID column (which is empty, right? It will be until prepStat.executeUpdate()). conn.prepareStatement() 返回了 ID 列(它是空的,对吗?直到 prepStat.executeUpdate())。

ResultSet rs = prepStat.getGeneratedKeys() - to be honest, I don't get it completely. ResultSet rs = prepStat.getGeneratedKeys() - 老实说,我没有完全理解。 It returns a ResultSet object containing the auto-generated key(s) generated by the execution of this Statement object. So what does it return in this case?它返回一个 ResultSet object,其中包含通过执行此语句 object 生成的自动生成的键。那么在这种情况下它返回什么? The ID column? ID栏? And in the if() we check if there's any not empty next ID and we assign the ID value from database to our id variable?在 if() 中,我们检查是否有任何非空的下一个 ID,并将数据库中的 ID 值分配给我们的 id 变量?

When you call prepareStatement() it does not return an actual row from the database yet.当您调用prepareStatement()时,它还没有从数据库返回实际的行。 Vaguely speaking, it sets a "query template" to send it to the database so the next time you do the same query (with other values) the database won't have to parse the query again.含糊地说,它设置了一个“查询模板”以将其发送到数据库,因此下次您执行相同的查询(使用其他值)时,数据库将不必再次解析查询。 Besides, and more important, it's a way to prevent sql injection.此外,更重要的是,它是一种防止 sql 注入的方法。

Anyway, in the last three lines you access the ResultSet data through a cursor which is initially positioned before the first row.无论如何,在最后三行中,您通过最初位于第一行之前的 cursor 访问ResultSet数据。 rs.next() moves the cursor to the first row and if it's present the if() statement should return true letting you retrieve the id of the inserted row. rs.next()将 cursor 移动到第一行,如果它存在, if()语句应返回true ,让您检索插入行的id

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

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