Qt's odbc driver does not support LastInsertId with mysql, whats the workaround?

守給你的承諾、 提交于 2020-01-06 07:58:10

问题


Im using Qt 4.8.3 and the MySQL ODBC 3.51 Driver. The driver does not seem to support LastInsertId which I test like this:

db.driver()->hasFeature(QSqlDriver::LastInsertId)

I need it to find the auto increment id I just inserted

query.exec("INSERT INTO myTable (MyVal, Created) VALUES ('1', NOW())");
auto insertId = query.lastInsertId().toString();

What is the best workaround?

EDIT: there will be concurrent access to this table from multiple clients.


回答1:


According to MySQL documentation, you can call:

SELECT LAST_INSERT_ID();

after the insert query to get the latest id inserted for the current connection, even when using ODBC.




回答2:


You could do something like:

query.exec("SELECT id FROM myTable ORDER BY id DESC LIMIT 1");

to get the largest id in your table - this should be the one you just inserted.

If you are writing an application that can have multiple concurrent users you'll have to look into creating a lock on your table and then releasing the lock after you run this second query.




回答3:


Use OUTPUT INSERTED.[Field Name] as in code below. Read the returned ID with next() function.

bool RepeatsRecognizer::InsertEvent(RepEvent* event){
QSqlDatabase db = AppManager::DB_Output()->ThreadDatabase();
QSqlQuery query(db);
query.prepare("INSERT INTO RepEvents (ChannelID, StatsRangeUID, MinStartDateTime, MaxDuration, Fixed) OUTPUT INSERTED.ID"
              " VALUES (?, ?, ?, ?, ?)");
query.bindValue(0, event->ChannelID);
query.bindValue(1, event->StatsRangeUID.toString());
query.bindValue(2, event->MinStartDateTime);
query.bindValue(3, event->MaxDuration);
query.bindValue(4, false);


if (!query.exec())
    return false;

if (!query.next())
    return false;

event->ID = query.value(0).toLongLong();
qDebug() << __FUNCTION__ << "Event ID:" << event->ID;

}



来源:https://stackoverflow.com/questions/13709117/qts-odbc-driver-does-not-support-lastinsertid-with-mysql-whats-the-workaround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!