c++ - 如何使用 QT Sqlite 插入多行?

标签 c++ sqlite qt transactions

我有以下代码(它是一个函数),我想在每次调用它时向我的数据库插入 500 个值。

QSqlDatabase::database().transaction();
query.prepare("INSERT INTO datatable (Name, age, data1, data2, data3, data4, data5)"
              "VALUES (?, ?, ?, ?, ?, ?, ?)");
for (int i = 0; i<500; i++){
    query.bindValue(0,Name[j]);
    query.bindValue(1,age[j]);
    query.bindValue(2,data1[j]);
    query.bindValue(3,data2[j]);
    query.bindValue(4,data3[j]);
    query.bindValue(5,data4[j]);
    query.bindValue(6,data5[j]);
    query.next();   //just trying to go for the next row
}
qDebug() << "Finish" << QSqlDatabase::database().commit();

问题是这只是从 j=500 时的值插入数据,我的意思是,这只存储最后的数据,而其他 499 没有存储。

谁能帮帮我?我曾尝试将查询放入准备好循环的内部,但效果不佳。

最佳答案

您必须使用 exec()方法而不是 next() :

QSqlDatabase db = QSqlDatabase::database();

if(db.transaction()){

    QSqlQuery query;
    query.prepare("INSERT INTO datatable (Name, age, data1, data2, data3, data4, data5) VALUES (?, ?, ?, ?, ?, ?, ?)");
    for (int i = 0; i < 500; i++){
        query.bindValue(0, Name[i]);
        query.bindValue(1, age[i]);
        query.bindValue(2, data1[i]);
        query.bindValue(3, data2[i]);
        query.bindValue(4, data3[i]);
        query.bindValue(5, data4[i]);
        query.bindValue(6, data5[i]);
        if(<b>!query.exec()</b>){
            qDebug() << query.lastError().text();
        }
    }

    if(!db.commit()){
        qDebug() << db.lastError().text();
    }
}

关于c++ - 如何使用 QT Sqlite 插入多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59200034/

相关文章:

c++ - 将子字符串传递给函数

c++ - C++中的指针与变速

c++ - CGAL新手问题: Which segments intersect?

android - 配置 Qt Creator 以将 Clang 与 Qt for Android 结合使用

c++ - 来自 jsonModel 的 QML 中的空 TreeView

c++ - 禁用 QTreeWidgetItem 的列或删除设置的 CheckBox

c++ - 包含类对象的最佳 C++ 设计是什么?

java - 使用正则表达式查询 Android SQLite 数据库

sql - 如何根据连接属性的最接近值左连接两个表?

php - 如何使用 Zend_Db 获取 Sqlite 数据库的最后插入 ID