5

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?

6
  • No, its the number of rows that has been modified according to your query. A primary key is not always a single integer you know. Commented Jan 9, 2013 at 11:32
  • int is the number rows affected means if you have executed one insert then int will be 1. Commented Jan 9, 2013 at 11:32
  • 5
    where does string.get(1) come from? Keep Little Bobby Tables in your mind! Commented Jan 9, 2013 at 11:36
  • OKI thx, but i still don't know if i can insert the row and get it's pk with 1 sql statment? Commented Jan 9, 2013 at 11:37
  • You can. The code I posted below works. Commented Jan 9, 2013 at 11:38

5 Answers 5

11

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);
Sign up to request clarification or add additional context in comments.

4 Comments

thank you! works like t a charm. only diffrent is that first parameter should be null like: VALUES (null, '"+ string.get(1) +"')
Or better yet, the OP should use a parametrized query
Please use a parameterized query. This code as presented is an SQL injection attack waiting to happen.
what if stmt.getGeneratedKeys() throws SQLException, how to delete inserted record?..
5

Pass Statement.RETURN_GENERATED_KEYS while creating PreparedStatement conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

and PreparedStatement#getGeneratedKeys() returns auto generated key after inert.

2 Comments

What will it it return if the SQL fails, like, for example, the SQL query was wrong?
on that case it will throw SQL Exception, find more documentation here. docs.oracle.com/javase/8/docs/api/java/sql/…
5

In order to get last inserted id look at the below code:

PreparedStatement stmnt = Conn.preparedStatement("INSERT INTO authors(col1) VALUES (?)", Statement. RETURN_GENERATED_KEYS );
stmnt.setString(col1val);
stmnt.executeUpdate();
ResultSet rs=stmnt.getGeneratedKeys();
if(rs.next()){
   System.out.println(rs.getInt(1));
}

Comments

0

I don't know if this is supported by JDBC (haven't used it in a while), but I guess you could try:

INSERT INTO TABLE_NAME (FIELD1, FIELD2) VALUES ('foo', 'bar') RETURNING FIELD3

via executeQuery() or, if your jdbc driver doesn't support RETURNING write a simple stored function.

Which RDMBS are you using?

Comments

0

Try:

INSERT INTO authors VALUES (...) returning authorID

When you execute it, do so with executeQuery. You should get back a ResultSet with one row and one column — it will be the ID.

3 Comments

ResultSet rs =stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"' returning authorID)"); doesn't work
@jeffranz use executeQuery
... and move the closing bracket from after authorID to before returning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.