Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java PreparedStatement retrieving last inserted ID [duplicate]

This answer to this question done this way seems to be very difficult to find on the internet. Basically I am inserting values into a MySQL database using PreparedStatement. I use the PreparedStatement to escape the data to prevent SQL Injection attacks. The problem is, there is now way retreving those keys.

String query="Insert INTO Table_A(name, age) (?, ?)"; //String query="Insert INTO Table_A(name, age) ('abc','123' )";//Doesn't escape PreparedStatement prest; prest = con.prepareStatement(query); prest.setString(1,"abc"); prest.setInt(2,123); prest.executeUpdate(); //prest.executeUpdate(query, PreparedStatement.RETURN_GENERATED_KEYS); Throws an error //prest.executeQuery(); Throws an error 

So how can I escape input and use PreparedStatements in Java?

like image 991
Devin Dixon Avatar asked Apr 01 '11 12:04

Devin Dixon


People also ask

What does PreparedStatement executeQuery return?

executeQuery. Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Can a PreparedStatement be reused?

Reusing a PreparedStatementOnce a PreparedStatement is prepared, it can be reused after execution. You reuse a PreparedStatement by setting new values for the parameters and then execute it again.

What does PreparedStatement executeUpdate return?

When the method executeUpdate is used to execute a DDL (data definition language) statement, such as in creating a table, it returns the int value of 0.

What does PreparedStatement setString do?

setString(1, usernameObject); setString(2, privilegeObject); The purpose of PreparedStatement is to reduce the difficulty and readability of the database connection code. when the developer has to use so many column values with Statement's instance it's so difficult to put semicolons, commas and plus (concat operator).


1 Answers

pass Statement.RETURN_GENERATED_KEYS in prepareStatement() along with your query. And then use getGeneratedKeys() of PreparedStatement to get the ResultSet containing your inserted auto_incremented_id.

String query="Insert INTO Table_A(name, age) (?, ?)";                 //String query="Insert INTO Table_A(name, age) ('abc','123' )";//Doesn't escape                 PreparedStatement prest;                 prest = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);                 prest.setString(1,"abc");                 prest.setInt(2,123);                 prest.executeUpdate();                 //prest.executeUpdate(query, PreparedStatement.RETURN_GENERATED_KEYS); Throws an error                 //prest.executeQuery(); Throws an error                 ResultSet rs = prest.getGeneratedKeys();                 if(rs.next())                 {                     int last_inserted_id = rs.getInt(1);                 } 
like image 98
Asad Avatar answered Oct 01 '22 12:10

Asad