What’s PLSQL (Oracle) equivalent of this SQL server snippet?
BEGIN TRAN
INSERT INTO mytable(content) VALUES ("test") -- assume there's an ID column that is autoincrement
SELECT @@IDENTITY
COMMIT TRAN
In C#, you can call myCommand.ExecuteScalar() to retrieve the ID of the new row.
How can I insert a new row in Oracle, and have JDBC get a copy of the new id?
EDIT:
BalusC provided a very good starting point. For some reason JDBC doesn’t like named parameter binding. This gives “Incorrectly set or registered parameters” SQLException. Why is this happening?
OracleConnection conn = getAppConnection();
String q = "BEGIN INSERT INTO tb (id) values (claim_seq.nextval) returning id into :newId; end;" ;
CallableStatement cs = (OracleCallableStatement) conn.prepareCall(q);
cs.registerOutParameter("newId", OracleTypes.NUMBER);
cs.execute();
int newId = cs.getInt("newId");
Normally you would use
Statement#getGeneratedKeys()for this (see also this answer for an example), but this is as far (still) not supported by the Oracle JDBC driver.Your best bet is to either make use of
CallableStatementwith aRETURNINGclause:Or fire
SELECT sequencename.CURRVALafterINSERTin the same transaction: