此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()
(例如,也请参见Statement#getGeneratedKeys()
),但是到目前为止(仍然)Oracle JDBC驱动程序不支持。您最好的选择是任一个>>通过this answer子句使用CallableStatement
:
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
它可能更简洁:
import static org.morejdbc.SqlTypes.BIGINT;
import static org.morejdbc.JdbcCall.callSql;
import static org.morejdbc.*;
...
Out<Long> idOut = Out.of(BIGINT);
jdbcTemplate.execute(callSql("BEGIN INSERT INTO mytable(id, content) VALUES (seq_mytable.NEXTVAL(), ?) "
+ "RETURNING id INTO ?; END;")
.in(content)
.out(BIGINT, idOut));
System.out.println("Id is " + idOut.get());