Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <p>From the Java API documentation for <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#execute%28java.lang.String%29" rel="noreferrer">Statement.executeQuery()</a>:</p> <blockquote> <p>Executes the given SQL statement, which returns a single ResultSet object.</p> <p>Parameters:</p> <p>sql - an SQL statement to be sent to the database, typically a <strong>static SQL SELECT statement</strong></p> </blockquote> <p>and from the Java API documentation for <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29" rel="noreferrer">Statement.executeUpdate()</a>:</p> <blockquote> <p>Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.</p> <p>Parameters:</p> <p>sql - an <strong>SQL Data Manipulation Language (DML) statement</strong>, such as INSERT, UPDATE or DELETE; or <strong>an SQL statement that returns nothing</strong>, such as a DDL statement.</p> </blockquote> <p>Your code (pseudo-code posted here) should appear as:</p> <pre><code>statement.executeUpdate("INSERT INTO Sessions(id_user) VALUES(1)"); // DML operation statement.executeQuery("SELECT LAST_INSERT_ID()"); // SELECT operation </code></pre> <p>And of course, the <a href="http://dev.mysql.com/doc/refman/5.5/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-last-insert-id" rel="noreferrer">MySQL documentation demonstrates how to perform the same activity for AUTO_INCREMENT columns</a>, which is apparently what you need.</p> <p>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:</p> <pre><code>statement.execute("INSERT INTO Sessions(id_user) VALUES(1); SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;"); </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload