简体   繁体   中英

Is it possible to get a auto-generated values when using statement.getGeneratedKeys() in MySQL?

I am connecting mysql via java. I am trying to insert a record and i am finding the status using statement.getGeneratedKeys() and then if (generatedKeys.next()) . Now can i get a value of coulmn which was inserted (ie) i have column named pass and it is an auto_increament column and it is my primary key and now i want to get the value which was inserted in this column. Is it possible??

The standard MySQL Connector J driver does support getting generated keys, yes. Here is some sample code:

final Connection conn ; // setup connection
final String SQL ; // define SQL template string

final PreparedStatement stmt = connection.prepareStatement(
    SQL,
    Statement.RETURN_GENERATED_KEYS);

int affected = stmt.executeUpdate();
if (affected > 0) {
    final ResultSet keySet = stmt.getGeneratedKeys();
    while (keySet.next()) {
        // these are your autogenerated keys, do something with them
        System.out.println(keySet.getInt(1));
    }
}

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