Qt使用 QSqlTableModel 模型操作数据库

来源:互联网 发布:js隐式全局变量 编辑:程序博客网 时间:2024/05/29 09:13
        Qt可以使用SQL语句完成对数据库的常规操作。如果不需要复杂的查询,QSqlTableModel模型基本可以满足需求。本文将针对QSqlTableModel模型操作sqlite进行说明。
        通常,Qt要进行SQL数据库操作,需要在 .pro 文件中加上这么一句:
QT += sql
        Qt默认的情况下会加载sqlite驱动,下面一段代码为创建一个数据库连接:
QSqlDatebase db = QSqlDatabase:addDatabase("QSQLITE");
db.setDatabaseName( "dbname.db");
if (!db.open()) {
QMessageBox::critical(0, QObject::tr("Database Error")), db.lastError().text());
}
        关于addDatabase(),可以指定名字(暂不叙述),如不指定,将采用系统默认的 QSqlDatabase::defaultConnection 这一名字。此时,Qt会创建一个默认的连接。此后,我们并不需要指定操作的是哪个数据库,而是使用当前的连接。
        接下来,我们需要为模型设置表:
QSqlTableModel model;
model.setTable("tablename");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
如下是Qt帮助文档中对setTable()的说明:
void QSqlTableModel::setTable(const QString & tableName)
 
Sets the database table on which the model operates to tableName. Does not select data from the table, but fetches its field information.
To populate the model with the table's data, call select().
// 设置要操作的数据库表。并没有从表中选择数据,而是获取它的字段。
// 如要用表中的数据填充模型,需调用 select()
设置表后,我们就可以应用QSqlTableModel模型进行数据库的基本操作了,即增、删、改、查。
          一、 
model.setFilter("age > 20 and age < 25");
if (model.select()) {
for (int i = 0; i < model.rowCount(); ++i) {
QSqlRecord record = model.record(i);
QString name = record.value("name").toString();
int age = record.value("age").toInt();
qDebug() << name << ": " << age;
}
}
        在Qt中,使用QSqlRecord来取出每一条数据,用value()返回相应字段的数据,随后我们可以根据需要转化为我们想要的数据类型。
        下面我们重点说一下setFilter(),如下是Qt帮助文档中对setFilter()的说明:
void QSqlTableModel::setFilter(const QString & filter)
 
The filter is a SQL WHERE clause without the keyword WHERE (for example, name='Josephine').
 
If the model is already populated with data from a database, the model re-selects it with the new filter. Otherwise, the filter will be applied the next time select() is called.
 
//filter是一个没有关键字WHERE的SQL语句
//如果当前模型已经从数据库中填充了数据,则立即应用新的过滤条件。否则,过滤条件将在下一次调用select()时生效。
        可知,setFilter()一般与select()一起使用。
        如下是Qt帮助文档中对select()的说明:
//如下是Qt对select的帮助文档
bool QSqlTableModel::select()
 
Populates the model with data from the table that was set via setTable(), using the specified filter and sort condition, and returns true if successful; otherwise returns false.
 
//根据指定的筛选和排序条件,用setTable所设置的表的数据填充模型,如果成功则返回true,否则返回false
        因此,我们可以这样做:① 在setTable后就调用select(),而不必每次调用select() ; ② 在每次调用setFilter()后调用select().
          二、增
QSqlRecord record = model->record();
record.setValue("name", "张三");
record.setValue("age", 12);
model->insertRecord(row, record);
model->submitAll();
        通常使用 insertRecord()来增加一行。
bool QSqlTableModel::insertRecord(int row, const QSqlRecord & record)
 
Inserts the record at position row. If row is negative, the record will be appended to the end. Calls insertRows() and setRecord() internally.
Returns true if the record could be inserted, otherwise false.
Changes are submitted immediately for OnFieldChange and OnRowChange. Failure does not leave a new row in the model.
 
//在参数row的位置插入一行。如果行不存在,则该记录将被附到结尾。
//若编辑策略为 OnManualSubmit或 OnRowChange 时,修改将立即生效。
bool QSqlTableModel::submitAll()
 
Submits all pending changes and returns true on success. Returns false on error, detailed error information can be obtained with lastError().
 
In OnManualSubmit, on success the model will be repopulated. Any views presenting it will lose their selections.
 
//提交待定的修改,成功则返回true。
//在OnManualSubmit模式下,成功后数据模型将会被重新填充。任何应用这个数据模型进行显示的控件将会失去原来的选择。
        若我们选用OnManualSubmit模式,则需要使用submitAll();
        三、改
        与insertRecord()类似,使用setRecord()来修改某一条记录,并同时需要注意在需要时调用submitAll()。
bool QSqlTableModel::setRecord(int row, const QSqlRecord & values)  
        四、删
        删较简单,使用removeRow,或removeRows实现。同样要注意submitAll()的使用。
bool QAbstractItemModel::removeRow(int row, const QModelIndex & parent = QModelIndex())
bool QAbstractItemModel::removeRows(int row, int count, const QModelIndex & parent = QModelIndex())
        关于用模型操作数据库的常用方法就是这些了,还有一些方法,用到了再查阅也是可以的。
        Qt Assistant是一个详尽具体的说明文档,凭借着文档,可以不看其他教程也可以使用Qt了。很多次因为网上没有足够的资料而举步不前,而查看他之后,每次都是恍然大悟,收获颇丰。因此,真的要养成遇到问题查阅Qt Assistant的好习惯。

1 0