【问题标题】:How to insert multiple rows wih QT Sqlite?如何使用 QT Sqlite 插入多行?
【发布时间】:2020-03-30 16:09:41
【问题描述】:

我有以下代码(它是一个函数),我想在调用它时向我的数据库插入 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没有被存储。

谁能帮帮我?我尝试将查询准备好 for 循环放入其中,但效果不佳。

【问题讨论】:

    标签: c++ sqlite qt transactions


    【解决方案1】:

    您必须使用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(!query.exec()){
                qDebug() << query.lastError().text();
            }
        }
    
        if(!db.commit()){
            qDebug() << db.lastError().text();
        }
    }

    【讨论】:

      【解决方案2】:

      query.next() 通常用于遍历数据读取器的行。您应该使用 query.exec() 在您的事务中插入数据。

      这里有一个很好的教程:https://katecpp.wordpress.com/2015/08/28/sqlite-with-qt/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-25
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-20
        相关资源
        最近更新 更多