Oracle OCI 获取最后插入行的 ID

Oracle OCI get id of last inserted row

我正在编写一个 C++ 代码,在某些时候需要获取最后插入的行的 ID。

基于 this link here 我编写了这段代码,但它只返回垃圾(无效字符):

    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);

关于如何修复它的任何想法?

如果你有 table:

CREATE TABLE mytable (
  ID      INT PRIMARY KEY,
  FIELD_A INT,
  FIELD_B INT
);

您可以创建一个序列:

CREATE SEQUENCE mytable__id__seq;

然后你可以通过一个过程完成所有插入(并且可以使用一个包将所有 create/read/update/delete 功能组合到一个地方)然后你可以在包中使用 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;
/

然后您可以使用 OCI 调用存储过程,并且只使用来自 out 参数的绑定值。有很多示例(即 here and here),您可以参考。