[SOLVED]Why QSqlQuery faild after first use ::prepare and ::exec?



  • @#include <QtCore/QCoreApplication>

    #include <qsqldatabase.h>
    #include <qsqlquery.h>
    #include <qvariant.h>
    #include <iostream>

    using namespace std;

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);
    QSqlDatabase sqlDatabase=QSqlDatabase::addDatabase("QSQLITE");
    sqlDatabase.setDatabaseName("my_database.db");
    sqlDatabase.open();
    QSqlQuery query;
    query.exec("create table test(id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar)");
    for(int i=0;i<3;i++)
    {
    cout<<query.prepare("insert into test values(:id,:name)")<<endl;
    query.bindValue(":id",NULL);
    query.bindValue(":name","Name");
    cout<<query.exec()<<endl;
    //query.exec("insert into test values(NULL,'Name')");
    }
    query.exec("select * from test");
    while(query.next())
    {
    cout<<query.value(0).toInt()<<endl;
    cout<<query.value(1).toString().toStdString()<<endl;
    }
    return a.exec();
    }
    @

    it can only insert once, after the first insertion, all query.exec() returns fail;



  • Hi!
    Change your insertion as:
    @for(int i=0;i<3;i++)
    {
    cout<<query.prepare("insert into test (name)values(:name)")<<endl;
    query.bindValue(":name","Name");
    cout<<query.exec()<<endl;
    //query.exec("insert into test values(NULL,'Name')");
    }@
    id field in your table is auto increment primary key, it means sqlite will care about this field.



  • Please get actual error .
    @
    query.lastError().text();
    @



  • Thx O(∩_∩)O

    [quote author="qxoz" date="1362130762"]Hi!
    Change your insertion as:
    @for(int i=0;i<3;i++)
    {
    cout<<query.prepare("insert into test (name)values(:name)")<<endl;
    query.bindValue(":name","Name");
    cout<<query.exec()<<endl;
    //query.exec("insert into test values(NULL,'Name')");
    }@
    id field in your table is auto increment primary key, it means sqlite will care about this field.[/quote]


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.