Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>Normally</em> you would use <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#getGeneratedKeys%28%29" rel="nofollow noreferrer"><code>Statement#getGeneratedKeys()</code></a> for this (see also <a href="https://stackoverflow.com/questions/1915166/jdbc-how-can-we-get-inserted-record-id-in-java/1915197#1915197">this answer</a> for an example), but this is as far (still) not supported by the Oracle JDBC driver.</p> <p>Your best bet is to <em>either</em> make use of <a href="http://download.oracle.com/javase/6/docs/api/java/sql/CallableStatement.html" rel="nofollow noreferrer"><code>CallableStatement</code></a> with a <code>RETURNING</code> clause:</p> <pre><code>String sql = "BEGIN INSERT INTO mytable(id, content) VALUES (seq_mytable.NEXTVAL(), ?) RETURNING id INTO ?; END;"; Connection connection = null; CallableStatement statement = null; try { connection = database.getConnection(); statement = connection.prepareCall(sql); statement.setString(1, "test"); statement.registerOutParameter(2, Types.NUMERIC); statement.execute(); int id = statement.getInt(2); // ... </code></pre> <p><em>Or</em> fire <code>SELECT sequencename.CURRVAL</code> after <code>INSERT</code> in the same transaction:</p> <pre><code>String sql_insert = "INSERT INTO mytable(content) VALUES (?)"; String sql_currval = "SELECT seq_mytable.CURRVAL FROM dual"; Connection connection = null; PreparedStatement statement = null; Statement currvalStatement = null; ResultSet currvalResultSet = null; try { connection = database.getConnection(); connection.setAutoCommit(false); statement = connection.prepareStatement(sql_insert); statement.setString(1, "test"); statement.executeUpdate(); currvalStatement = connection.createStatement(); currvalResultSet = currvalStatement.executeQuery(sql_currval); if (currvalResultSet.next()) { int id = currvalResultSet.getInt(1); } connection.commit(); // ... </code></pre>
 

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