Oracle OCI获取最后插入行的id

时间:2016-04-15 21:26:39

标签: c++ oracle oci

我正在写一个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);

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

1 个答案:

答案 0 :(得分:2)

如果你有一张桌子:

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

您可以创建一个序列:

CREATE SEQUENCE mytable__id__seq;

然后你可以通过一个过程完成所有插入(并且可以使用一个包将所有创建/读取/更新/删除功能组合在一起)然后你可以在包中使用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参数中的绑定值。您可以参考很多示例(例如herehere)。