简体   繁体   中英

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()).

ResultSet rs = prepStat.getGeneratedKeys() - to be honest, I don't get it completely. 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? The ID column? 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?

When you call prepareStatement() it does not return an actual row from the database yet. 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.

Anyway, in the last three lines you access the ResultSet data through a cursor which is initially positioned before the first row. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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