How can I execute the following query and retrieve a result via prepared statement:
INSERT INTO vcVisitors (sid) VALUES (?); SELECT LAST_INSERT_ID();
Is there a way to execute both two statements at once?
I’ve tried to do the following:
Connection con = DbManager.getConnection();
PreparedStatement ps = con.PrepareStatement(
"INSERT INTO vcVisitors (sid) VALUES (?); SELECT LAST_INSERT_ID();");
ps.setInt(1, 10);
ResultSet rs = ps.exequteQuery();
rs.next();
return rs.getInt("LAST_INSERT_ID()");
but it gives me an error that executeQuery can’t execute such a query,
I’ve also tried to replace executeQuery by the following:
ps.execute();
rs = ps.getResultSet();
but it gives me SQL syntax error:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near 'SELECT LAST_INSERT_ID()' at line 1
but there are no problems with executing query
“INSERT INTO vcVisitors (sid) VALUES (’10’); SELECT LAST_INSERT_ID();” directly from mysql console.
While updating (inserting) data use
executeUpdateinstead ofexecuteQuery. Try executingSELECT LAST_INSERT_ID()as another query.But it is not portable query. I suggest using
Statement.getGeneratedKeysinstead. Please look here: JDBC (MySQL) Retrieving AUTO_INCREMENT Column Values.Here is an example of properly used LAST_INSERT_ID():
and here the same with getGeneratedKeys: