【发布时间】: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
main() 函数:-
#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 实际上只有标题(表格的列),但没有行。
【问题讨论】:
-
query与db没有任何关联。您希望它在哪个数据库上运行?你不想在数据库打开后实际使用db变量吗? -
@Igor Tandetnik 然后首先创建表。我认为默认情况下查询连接到默认数据库。