[英]C++ MySql get last inserted id
I´m having the following code that insert a row into mysql database and return the inserted id: 我正在使用以下代码,将一行插入mysql数据库并返回插入的ID:
/*
* Execute the statement
*/
std::string sql = "INSERT INTO TABLE (A, B, C) VALUES (1, 2, 3)";
sql::Statement *stmt;
stmt = connection->createStatement();
stmt->execute(sql);
/*
* Get the returned id
*/
stmt = connection->createStatement();
sql::ResultSet *res = stmt->executeQuery("SELECT @@identity AS id");
res->next();
model.modelId = res->getInt64("id");
My questions are: 我的问题是:
Do I really need to call connection->createStatement()
again ? 我真的需要再次调用
connection->createStatement()
吗? I think this may overload the code, as I need to call twice the database. 我认为这可能会使代码超载,因为我需要调用两次数据库。
Is there a way to optimize this code ? 有没有一种方法可以优化此代码?
Is there other way to get the last inserted id ? 还有其他方法来获取最后插入的id吗?
Thanks for helping. 感谢您的帮助。
Just for the reference, @@identity
is MSSQL-specific system function , that also returns last-insert id but for MSSQL, not for MySQL. 仅供参考,
@@identity
是特定于MSSQL的系统函数 ,该函数还会返回最后插入的ID,但返回的是MSSQL,而不是MySQL。
To get last-insert id in MySQL, since you have asked specifically for MySQL, you need to change your SELECT statement to following: 为了获得MySQL中的最后插入ID,由于您专门询问了MySQL,因此需要将SELECT语句更改为以下内容:
SELECT LAST_INSERT_ID() AS id;
Also, since stmt->execute()
and stmt->executeQuery()
methods take String , as input argument, I am sure that you don't need to connection->createStatement()
again. 此外,由于
stmt->execute()
和stmt->executeQuery()
方法采用String作为输入参数,因此我确定您无需再次connection->createStatement()
。 Just to confirm, I just googled it and found this link . 只是为了确认,我只是在Google上搜索并找到了此链接 。
Please note that this answer is specifically for MySQL, as this question is about MySQL. 请注意,此答案专门针对MySQL,因为此问题与MySQL有关。 Hope it helps.
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.