c++ - last_insert_id 的返回总是正确的吗?

标签 c++ mysql mariadb

如果我有以下两个功能:

int AccessDb::InsertColValue(string tableName, string col, string val)
{
    try
    {
        sql::Statement *stmt;
        bool ret;

        if ((nomTable != "") && (col != "") && (val != ""))
        {
            string query = "INSERT INTO " + tableName + "(" + col + ") values (";
                    query += val + ");";

            stmt = con->createStatement();
            ret = stmt->execute(query);
        }

        delete stmt;

        return 0;
    }
    catch (sql::SQLException &e)
    {
        return -1;
    }
}

long AccessDb::LastInsertId()
{
    try
    {
        sql::Statement *stmt;
        sql::ResultSet *res;

        string query = "SELECT LAST_INSERT_ID() AS LAST_ID";

        stmt = con->createStatement();
        res = stmt->executeQuery(query);

        delete stmt;

        long lastId;
        while (res->next())
        {
            lastId = res->getInt("LAST_ID");
        }

        return lastId;
    }
    catch (sql::SQLException &e)
    {
      return -1;
    }
}

如果我编写以下行并且该 ID 是由数据库自动生成的,我能否确定 LastInsertId() 的返回将始终为我提供正确的 ID?

AccessDb adb; // initialize the connexion with the db
int ret = adb.InsertColValue("people", "name", "John");
if (ret == 0)
    long lastId = adb.LastInsertId();

如果之前的代码同时在其他地方调用,我的 lastId 变量中的值是否会错误?如果是,我是否必须在我的 table 上使用锁定和解锁来避免这种情况或其他解决方案?

最佳答案

文档是这样说的:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

因此,除非您自己的客户端代码在多个线程之间共享连接(看起来您不是,因为您的代码中没有互斥锁或锁),您可以确定 SELECT LAST_INSERT_ID() 不是'不要与任何其他连接或客户端混淆。

我找不到 C++ mysql 库的文档,但验证 ret = stmt->execute(query); 在你的 InsertColValue() 中的返回值是什么> function 意味着,这样你就可以确定你无法插入任何东西的唯一可能方法是抛出异常。

关于c++ - last_insert_id 的返回总是正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27289076/

相关文章:

c++ - 尝试从 dll 调用 extern "C"函数的链接器错误

c++ - 复制构造函数中初始化列表中的 make_unique 是不使用 noexcept 说明符的良好目的吗?

c++ - 不知道如何从冒泡排序函数返回值

php - Laravel 迁移返回无效的 SQL

c++ - boost.test - 区分来自同一项目的不同构建配置的测试结果

sql - 如何获取Viditymart的产品总数?

mysql - 仅使用一张表来存储多种类型的关系,是否高效?

c# - 如何保证门票不会超售?

mysql - 计数并拆分到mysql中

MySQL (MariaDB - 10.0.16-MariaDB-1 (Debian) 奇怪的性能问题