Oracle使用OCCI和C++获取最后插入的行id

Oracle get last inserted row id using OCCI and C++

本文关键字:插入 id 最后 获取 使用 OCCI C++ Oracle      更新时间:2023-10-16

给定上面的代码,我如何获取插入数据库的行的ID。我正在使用C++和oracle OCCI接口:

    std::stringstream sqlStream("");
    sqlStream << "INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (1, 2, 3) RETURNING ID INTO :my_id_param";
    std::string sql(sqlStream.str());
    std::cout << sql << std::endl;
    std::unique_ptr<oracle::occi::Statement> stmt(connection->createStatement());
    stmt->execute(sql.c_str());
    //??? How can I access here the my_id_param ?

谢谢你的帮助。

您可以使用匿名PL/SQL并注册OUT参数来捕获生成的ID。这直接适用于序列,我还没有尝试过在触发器中使用序列。

std::stringstream sqlStream("");
sqlStream << "BEGIN INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (1, 2, 3) RETURNING ID INTO :1; END;";
std::string sql(sqlStream.str());
std::cout << sql << std::endl;
std::unique_ptr<oracle::occi::Statement> stmt(connection->createStatement(sql.c_str()));
stmt->registerOutParam(1, oracle::occi::OCCIINT);
stmt->executeUpdate();
int id = stmt->get(1);
// Use id...