Search code examples
javamysqlinsertlast-insert-id

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??


Solution

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