【问题标题】:Qt Sql INSERT statement has no effectQt Sql INSERT 语句没有效果
【发布时间】:2015-06-30 14:16:23
【问题描述】:

我在 Windows 上使用 Qt 4.8。在简单的程序中 INSERT 语句似乎不起作用。基本调试语句不显示任何错误字符串。谷歌帮不了我。在 SO similar question 存在。

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

ma​​in() 函数:-

#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();
}

我的输出 TableView 实际上只有标题(表格的列),但没有行。

【问题讨论】:

  • querydb 没有任何关联。您希望它在哪个数据库上运行?你不想在数据库打开后实际使用db 变量吗?
  • @Igor Tandetnik 然后首先创建表。我认为默认情况下查询连接到默认数据库。

标签: c++ sql qt sqlite


【解决方案1】:

您必须调用 QSqlTableModel::select() 以使用数据填充模型。

这在QSqlTableModel class的详细描述中有解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2021-12-27
    相关资源
    最近更新 更多