I have a table of authors : authorID, authorName. authorID is a pk with auto increment.
I'd like to write a method in java that gets a name from user and adds it to the table. however i need to return the id of the author. is there a way to do that with 1 sql statement?
for example if my code has the command:
stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"')");
which string.get(1) is the author name.
Now if i write:
ResultSet rs =stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"')");
it says error as rs is resultset but the returned value is int. is this int the pk of the row that i have inserted?
try
stmt.executeUpdate("INSERT INTO authors VALUES (, '"+ string.get(1) +"')", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
long pk = rs.getLong(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With