这个SQL Server片段的PLSQL(Oracle)等效项是什么?
BEGIN TRAN INSERT INTO mytable(content) VALUES ("test") -- assume there's an ID column that is autoincrement SELECT @@IDENTITY COMMIT TRAN
在C#中,您可以调用myCommand.ExecuteScalar()来检索新行的ID。
如何在Oracle中插入新行,并让JDBC获得新ID的副本?
编辑: BalusC提供了一个很好的起点。由于某种原因,JDBC不喜欢命名参数绑定。这给出了“错误设置或注册的参数” SQLException。为什么会这样呢?
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");
通常, 您将使用Statement#getGeneratedKeys()此方法,但是到目前为止(仍然)Oracle JDBC驱动程序不支持此方法。
Statement#getGeneratedKeys()
最好的办法是 要么 化妆使用的CallableStatement一个RETURNING条款:
CallableStatement
RETURNING
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); // ...
或 在同一笔交易SELECT sequencename.CURRVAL后开火INSERT:
SELECT sequencename.CURRVAL
INSERT
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(); // ...