MySQL C ++连接器:获取insert_id [英] MySQL C++ Connector: Get the insert_id
问题描述
我正在使用mysql连接器C ++.我的表中有一个auto_increament列,我想在执行插入操作时获取插入ID.有人知道如何获得吗?谢谢.
I am using mysql connector C++. There is an auto_increament column in my table, I want to get the insert id when I perform an insert action. Does someone know how to get it? Thanks.
我的代码如下:
conn->setAutoCommit(0);
pstmt.reset(conn->prepareStatement(insertStr.c_str()));
int updateCount = pstmt->executeUpdate();
conn->commit();
推荐答案
如果您使用的库的API没有提供检索last_insert_id的方法(对于C ++连接器来说似乎是这种情况),您可以随时进行查询
If the API of the library you are using does not provide a method to retrieve the last_insert_id (which seems to be the case for the C++ Connector) you can always do a query
SELECT LAST_INSERT_ID();
SELECT LAST_INSERT_ID();
,它为您提供了表示由于最近执行的INSERT语句而成功为AUTO_INCREMENT列成功插入的第一个自动生成的值的值". 有关MySQL的说明,请参见此处文档
which gives you the "value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement." See here for the explanation of MySQL's documentation
更新:
我从某用户中找到了此帖子的意思是,如果您不对字段使用auto_increment,则可以使用
I found this post from a user who is saying the if you do not use auto_increment on your field you can use
选择 @@ identity AS ID;
SELECT @@identity AS id;
这篇关于MySQL C ++连接器:获取insert_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!