Best unofficial Apache Server developers community |
|
I use I need insert and get id. My query:
error -
How insert and get id?
posted via StackOverflow
|
|
 
|
For non-select SQL statements you use To get the last inserted id, you can do this SQL statement.
Although there's probably an java wrapper for that select statement. Links: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html |
|
 
|
Connection connection = null; PreparedStatement preparedStatement = null; ResultSet generatedKeys = null;
|
|
 
|
You will need to use the executeUpdate() method to execute the INSERT statement, while you'll need to use the executeQuery() method to execute the SELECT statement. This is due to the requirements imposed by the JDBC specification on their usages: From the Java API documentation for Statement.executeQuery():
and from the Java API documentation for Statement.executeUpdate():
Your code (pseudo-code posted here) should appear as:
And of course, the MySQL documentation demonstrates how to perform the same activity for AUTO_INCREMENT columns, which is apparently what you need. If you need to execute both of them together in the same transaction, by submitting the statements in one string with a semi-colon separating them like the following:
then you'll need to use the execute() method. Note, that this depends on the support offered by the Database and the JDBC driver for batching statements together in a single execute(). This is supported in Sybase and MSSQL Server, but I do not think it is supported in MySQL. |