Problems with Open-Source Downloads read https://www.qt.io/blog/problem-with-open-source-downloads and https://forum.qt.io/post/638946

Trouble with QSqlRecord class



  • I am creating a database with SQLite and I am trying to insert information with the QSqlRecord class but it doesn't work at all. I created a class for the database called "DatabaseManager". This class contains a QSqlDatabase object which I manipulate to create my table. I successfully create the database using QSqlQuery:

    bool DatabaseManager::createNamesTable() {

    bool ret = false;
    QSqlQuery query;

    // db is the database object
    if(db.isOpen()) {
    ret = query.exec("CREATE TABLE names ("
    "id INTEGER,"
    "firstname VARCHAR(30),"
    "lastname VARCHAR(30)"
    ")");
    }

    return ret;
    

    }

    Unfortunately, when I try to use the QSqlRecord class, nothing happens. It doesn't even give an error. This is the definition in the .cpp file of DatabaseManager.

    void DatabaseManager::insertField(const QString &tableName, int pos, const QString &fieldName,
    QVariant::Type type) {
    db.record(tableName).insert(pos, QSqlField(fieldName, type));
    }

    And in the main(), I write:

    int main(int argc, char** argv)
    {
    QCoreApplication app(argc, argv);

    DatabaseManager db("New.db.sqlite");
    

    if( db.createNamesTable()) {
    db.insertField("names", 3, "places", QVariant::String); // here, i try to add a column called "places"
    qDebug() << "Does names contain places? " << db.contains("names", "places");
    }

    app.exec();
    

    }

    I'm completely confused on what I'm doing wrong! Any form of help would be appreciated!



  • hi daGenie,

    I think you missed this statement.

    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );

    This statement helps to get the already existed database connection object.



  • [quote author="Vittal" date="1373873277"]hi daGenie,

    I think you missed this statement.

    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );

    This statement helps to get the already existed database connection object.[/quote]

    Thanks for the reply.

    That statement is in the constructor of the DatabaseManager class but unfortunately, it still doesn't work.



  • ok friend ,

    send error report.Database connection management is easiest programming in Qt ,so its not a big problem.I always help u.



  • [quote author="Vittal" date="1373880559"]ok friend ,

    send error report.Database connection management is easiest programming in Qt ,so its not a big problem.I always help u.[/quote]

    Do you mean I should call the lastError().text() function and send the results? If that is the case, I have already tried that, and it returns an empty string which means "no error" I suppose.


Log in to reply