[英]Oracle OCI get id of last inserted row
I´m writing a C++ code that in some point needs to get the ID of the last inserted row. 我正在编写C ++代码,在某些情况下需要获取最后插入的行的ID。
Based on this link here I made up this code, but it is returning only trash (invalid characters): 根据此处的链接,我编写了以下代码,但它仅返回垃圾箱(无效字符):
std::string sql = "INSERT INTO MYTABLE (FIELD_A, FIELD_B) VALUES (10, 20)";
OCIStmt *stmthp;
int sts = OCIHandleAlloc( (dvoid *) envhp, (dvoid **) &stmthp, OCI_HTYPE_STMT, (size_t) 0, (dvoid **) 0);
CheckOracleError(sts);
sts = OCIStmtPrepare(stmthp, errhp, (const OraText *) sql.c_str(), (ub4) sql.size(), (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT);
CheckOracleError(sts);
sts = OCIStmtExecute(svchp, stmthp, errhp, (ub4) 1, (ub4) 0, (CONST OCISnapshot *) NULL, (OCISnapshot *) NULL, OCI_COMMIT_ON_SUCCESS);
if (sts != OCI_NO_DATA && sts != OCI_SUCCESS)
CheckOracleError(sts);
OraText rowID[19]; // Extra char for null termination.
ub2 size = 18;
OCIRowid *pRowID;
std::memset(rowID, 0, 19); // Set to all nulls so that string will be null terminated.
OCIDescriptorAlloc(envhp, (void**)&pRowID, OCI_DTYPE_ROWID, 0, NULL);
OCIAttrGet(stmthp, OCI_HTYPE_STMT, pRowID, 0, OCI_ATTR_ROWID, errhp);
OCIRowidToChar(pRowID, rowID, &size, errhp);
OCIHandleFree(stmthp, OCI_HTYPE_STMT);
Any ideas on how to fix it ? 关于如何解决它的任何想法?
If you have a table: 如果您有一张桌子:
CREATE TABLE mytable (
ID INT PRIMARY KEY,
FIELD_A INT,
FIELD_B INT
);
You can create a sequence: 您可以创建一个序列:
CREATE SEQUENCE mytable__id__seq;
Then you can do all the inserts via a procedure (and can use a package to group all the create/read/update/delete functionality together into one place) then you can use RETURNING .. INTO ..
within the package and get the value from an out variable: 然后,您可以通过一个过程进行所有插入(并可以使用一个程序包将所有创建/读取/更新/删除功能分组到一个位置),然后可以在程序包中使用
RETURNING .. INTO ..
并获取值从一个out变量:
CREATE OR REPLACE PACKAGE mytable_pkg
AS
PROCEDURE add(
i_field_a IN MYTABLE.FIELD_A%TYPE,
i_field_b IN MYTABLE.FIELD_B%TYPE,
o_id OUT MYTABLE.ID%TYPE
);
-- PROCEDURE edit( ... );
-- PROCEDURE del( ... );
END mytable_pkg;
/
CREATE OR REPLACE PACKAGE BODY mytable_pkg
AS
PROCEDURE add(
i_field_a IN MYTABLE.FIELD_A%TYPE,
i_field_b IN MYTABLE.FIELD_B%TYPE,
o_id OUT MYTABLE.ID%TYPE
)
AS
BEGIN
INSERT INTO mytable (
id,
field_a,
field_b
) VALUES (
mytable__id__seq.NEXTVAL,
i_field_a,
i_field_b
)
RETURNING id INTO o_id;
END add;
-- PROCEDURE edit( ... );
-- PROCEDURE del( ... );
END mytable_pkg;
/
Then you can call the stored procedure using OCI and just use the bound value from the out parameter. 然后,您可以使用OCI调用存储过程,而仅使用out参数中的绑定值。 There are plenty of examples (ie here and here ) that you can refer to.
您可以参考很多示例(即此处和此处 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.