0

I am using Qt 4.8 on Windows. In the simple program INSERT statement does not seem to be working. Basic debugging statements doesn't show any error string. Google could not help me. on SO similar question exists.

sql.h

#ifndef SQL_H
#define SQL_H
#include<QtSql>
#include<QtGui>
#include<QDebug>
class Unit
{
public:
    Unit()
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("x");
        bool ok = db.open();

        QSqlQuery query;
        query.exec("create table vidyarthi(section integer(10), unit integer(10), details varchar(500));");


        query.exec("insert into vidyarthi values( 1,2,'Hello world');");

        qDebug()<<query.lastError().databaseText(); // prints "" means empty
        qDebug()<<query.lastError().text(); // prints  "" means empty


        QSqlTableModel *tmodel=new QSqlTableModel;
        tmodel->setTable("vidyarthi");
        qDebug()<<tmodel->rowCount(); // prints 0


        QTableView *tv=new QTableView;
        tv->setModel(tmodel);
        tv->show();
    }

};

#endif // SQL_H

The main() function:-

#include "widget.h"
#include <QApplication>
#include<QtCore>
#include<sql.h>
int main(int argc, char *argv[])
{
   QApplication a(argc, argv);

    Unit unit;

   return a.exec();
}

My output TableView has only just headers actually (columns of the table) but no rows.

2
  • 1
    query is not in any way connected to db. Which database do you expect it to operate on? Don't you want to actually use db variable once the database is opened? Commented Jun 30, 2015 at 14:19
  • 1
    @Igor Tandetnik then how the table was created first. I think by default query is connected to the default db. Commented Jun 30, 2015 at 14:24

1 Answer 1

3

You have to call QSqlTableModel::select() to populate the model with data.

This is explained in the detailled description of the QSqlTableModel class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.