0

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

Perception
  • 79,279
  • 19
  • 185
  • 195
ACP
  • 34,682
  • 100
  • 231
  • 371

1 Answers1

2

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));
    }
}
Perception
  • 79,279
  • 19
  • 185
  • 195
  • Still I am getting java.sql.SQLException: Column 'pass' not found error. – ACP Mar 25 '13 at 12:52
  • You are not going to get that while iterating generated keys. Are you sure your insert statement isnt mismatching with your table schema? – Perception Mar 25 '13 at 13:11