Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA with SQL: the return value of insert command?

Tags:

java

sql

jdbc

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?

like image 256
jeff ranz Avatar asked Dec 01 '22 20:12

jeff ranz


1 Answers

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);
like image 95
Evgeniy Dorofeev Avatar answered Dec 04 '22 09:12

Evgeniy Dorofeev