草庐IT

c++ - MySQL C++ 连接器如何从插入查询中检索自动递增键

coder 2023-10-24 原文

我正在使用 mysql C++ 连接器。我有一张 table :

CREATE TABLE some_table 
(
    id INT NOT NULL AUTO_INCREMENT, 
    col1 INT, 
    col2 INT,
    PRIMARY KEY ( id )
);

要在查询中插入多条记录,我使用:

INSERT INTO some_table
    (col1, col2)
VALUES
    (0, 1),
    (2, 3),
    (4, 5);

我的问题是:插入后,我想检索所有自动生成的 ID。是否可以在不创建另一个查询的情况下使用 C++ 连接器中的函数?

例如,在 JDBC 中,可以使用以下方法检索 AUTO_INCREMENT 列值。

stmt.executeUpdate(
        "INSERT INTO autoIncTutorial (dataField) "
        + "values ('Can I Get the Auto Increment Field?')",
        Statement.RETURN_GENERATED_KEYS);

//
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
//

int autoIncKeyFromApi = -1;

rs = stmt.getGeneratedKeys();

if (rs.next()) {
    autoIncKeyFromApi = rs.getInt(1);
} else {

    // throw an exception from here
}

https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-last-insert-id.html

有任何 C++ 连接器替代方案吗?

谢谢

最佳答案

去年我遇到了同样的问题。解决方案是使用内置的 LAST_INSERT_ID() .下面我更改了 getting start example 2展示如何使用它:

    //previous variable declarations and initialisation similar to the original example
    driver = get_driver_instance();
    con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
    con->setSchema("test_schema");

    con->setAutoCommit(false);

    stmt = con->createStatement();
    stmt->execute("DROP TABLE IF EXISTS tbl__test1");
    stmt->execute("DROP TABLE IF EXISTS tbl_test2");

    const string createTbl1Statement = "CREATE TABLE `tbl__test1` ("
            "`id` int(11) NOT NULL AUTO_INCREMENT,"
            "`col_value` varchar(45) DEFAULT NULL,"
            "PRIMARY KEY (`id`)"
            ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";

    const string createTbl2Statement = "CREATE TABLE `tbl_test2` ("
            "`id` int(11) NOT NULL AUTO_INCREMENT,"
            "`tbl_test1_id` int(11) NOT NULL,"
            "`col_value` varchar(45) DEFAULT NULL,"
            "PRIMARY KEY (`id`)"
            ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";

    stmt->execute(createTbl1Statement);
    stmt->execute(createTbl2Statement);

    pstmt = con->prepareStatement(
            "INSERT INTO tbl__test1(col_value) VALUES ('abcde')");
    pstmt->executeUpdate();
    delete pstmt;

    stmt->execute("SET @lastInsertId = LAST_INSERT_ID()");
    delete stmt;

    const string insertTbl2 = "INSERT INTO tbl_test2(tbl_test1_id, col_value)" 
            " VALUES (@lastInsertId, '1234')";

    pstmt = con->prepareStatement(insertTbl2);
    pstmt->executeUpdate();
    delete pstmt;

    con->commit();

    delete con;
    //remain code is like the example 2 from mysql site

关于调用 LAST_INSERT_ID() 的安全性,如 mysql 文档所述:

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.

编辑:

如给定here :

With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.

因此,LAST_INSERT_ID 返回最后生成的 ID,而不管新行插入到哪个表。如果您需要插入多行,只需在插入每一行后立即调用 LAST_INSERT_ID,这样您就可以获取 key 。

在下面的代码中,它在表 1 中插入 1 行,获取生成的键(返回“1”),然后该键用于在关联表 2 中插入新闻 2 行。然后再次插入 1 个新行表1中的行,再次获取生成的键(返回'2')并在表2中再次插入2条新闻行:

#include <stdlib.h>
#include <iostream>

#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

using namespace std;

int main(void) {
    cout << endl;
    cout << "Let's have MySQL count from 10 to 1..." << endl;

    try {
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::PreparedStatement *pstmt1;
        sql::PreparedStatement *pstmt2;

        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
        con->setSchema("test_schema");

        con->setAutoCommit(false);

        stmt = con->createStatement();
        stmt->execute("DROP TABLE IF EXISTS tbl__test1");
        stmt->execute("DROP TABLE IF EXISTS tbl_test2");

        const string createTbl1Statement = "CREATE TABLE `tbl__test1` ("
            "`id` int(11) NOT NULL AUTO_INCREMENT,"
            "`col_value` varchar(45) DEFAULT NULL,"
            "PRIMARY KEY (`id`)"
            ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";

        const string createTbl2Statement = "CREATE TABLE `tbl_test2` ("
            "`id` int(11) NOT NULL AUTO_INCREMENT,"
            "`tbl_test1_id` int(11) NOT NULL,"
            "`col_value` varchar(45) DEFAULT NULL,"
            "PRIMARY KEY (`id`)"
            ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";

        stmt->execute(createTbl1Statement);
        stmt->execute(createTbl2Statement);

        pstmt1 = con->prepareStatement(
            "INSERT INTO tbl__test1(col_value) VALUES (?)");

        pstmt1->setString(1, "abcde");
        pstmt1->executeUpdate();

        stmt->execute("SET @lastInsertId = LAST_INSERT_ID()");

        const string insertTbl2 =
            "INSERT INTO tbl_test2(tbl_test1_id, col_value)"
                    " VALUES (@lastInsertId, ?)";
        pstmt2 = con->prepareStatement(insertTbl2);

        pstmt2->setString(1, "child value 1");
        pstmt2->executeUpdate();

        pstmt2->setString(1, "child value 2");
        pstmt2->executeUpdate();

        pstmt1->setString(1, "xpto");
        pstmt1->executeUpdate();

        stmt->execute("SET @lastInsertId = LAST_INSERT_ID()");

        pstmt2->setString(1, "child value 3");
        pstmt2->executeUpdate();

        pstmt2->setString(1, "child value 4");
        pstmt2->executeUpdate();

        con->commit();

        delete stmt;
        delete pstmt1;
        delete pstmt2;

        delete con;

    } catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    cout << endl;

    return EXIT_SUCCESS;
}

结果是表 1 中的 2 行:

表 2 中的 4 行每行都与表 1 中的键正确关联:

因此,关键是在使用您需要的生成键插入新行后调用 LAST_INSERT_ID()。

关于c++ - MySQL C++ 连接器如何从插入查询中检索自动递增键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800465/

有关c++ - MySQL C++ 连接器如何从插入查询中检索自动递增键的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  7. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

随机推荐