【问题标题】:DBExpress and mysql last insert idDBExpress 和 mysql 最后插入 id
【发布时间】:2016-10-06 22:26:44
【问题描述】:

有几篇关于如何从 MySQL 获取 last_insert_id 和相关问题的帖子。我找到了一篇与 DBExpress 相关的帖子:delphi dxExpress MySQL: invalid LAST_INSERT_ID value

但是,在该帖子之后不要帮助我使用以下代码将注释插入到注释表中。

TSQLQuery* tq = new TSQLQuery(NULL);
tq->SQLConnection = atdbDM->SQLConnection1;

stringstream q;
q <<"INSERT INTO note (created_by, note) VALUES ("<<1234<<", \'<none>\');";
q << "SELECT LAST_INSERT_ID() AS lastNoteID;";
tq->SQL->Add(q.str().c_str());
tq->Open();
int noteID = tq->FieldByName("lastNoteID")->AsInteger;
tq->Close();

当 Open() 执行时,我得到一个异常:

'You have an error in your SQL syntax; Check the manual that correposnds to   your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID... at line1'

如果我先执行插入语句,然后单独执行 SELECT 语句,则不会出错,但返回的 ID 始终为 0。 有谁知道需要改什么?我正在使用 C++ Builder XE3

【问题讨论】:

  • LAST_INSERT_ID() 是成功插入的最后插入的 ID。如果您的记录未插入或更新,则此值不会更改。 MySQL 网站上的许多讨论。我通过数据字段定位记录,然后加载 ID 字段,不信任 LAST_INSERT_ID()。
  • 这里的问题不是 LAST_INSERT_ID() 本身。问题似乎是 DBExpress 和 MySQL 的组合最终说上述查询无效。为 id 获取 0 似乎通常与属于两个不同会话的单独查询相关联。

标签: c++ mysql c++builder dbexpress


【解决方案1】:

我发现为了防止创建多个会话,导致last_insertid函数总是返回0,可以将connections AUTOCLONE参数设置为false。然后最后一个插入 id 函数工作正常。即:

MySQLConnection->Connected = true;
MySQLConnection->AutoClone = false; //<- makes last_insert_id work as expected!

【讨论】:

    猜你喜欢
    • 2012-05-31
    • 2010-10-21
    • 2011-06-01
    • 1970-01-01
    • 2011-11-06
    • 2014-09-06
    • 1970-01-01
    • 2015-09-30
    • 2017-10-14
    相关资源
    最近更新 更多