QSqlQueryModel的实例操作
QSqlQueryModel类为SQL的结果集提供了一个只读的数据模型,下面我们先利用这个类进行一个最简单的操作。
1. #ifndef DATABASE_H
2.
3. #define DATABASE_H
4.
5. #include <QSqlDatabase>
6. #include <QSqlQuery>
7.
8. static bool createConnection()
9. {
10. QSqlDatabase db = QSqlDatabase::addDatabase(“QSQLITE”);
11. db.setDatabaseName(“database.db”);
12. if(!db.open()) return false;
13. QSqlQuery query;
14. query.exec(“create table student (id int primary key, name vchar)”);
15. query.exec(“insert into student values (0,’yafei0′)”);
16. query.exec(“insert into student values (1,’yafei1′)”);
17. query.exec(“insert into student values (2,’yafei2′)”);
18. return true;
19. }
20. #endif // DATABASE_H
1. #include <QtGui/QApplication>
2. #include “widget.h”
3. #include “database.h”
4. int main(int argc, char *argv[])
5. {
6. QApplication a(argc, argv);
7. if(!createConnection())
8. return 1;
9. Widget w;
10. w.show();
11. return a.exec();
12. }
1. void Widget::on_pushButton_clicked()
2. {
3. QSqlQueryModel *model = new QSqlQueryModel;
4. model->setQuery(“select * from student”);
5. model->setHeaderData(0, Qt::Horizontal, tr(“id”));
6. model->setHeaderData(1, Qt::Horizontal, tr(“name”));
7. QTableView *view = new QTableView;
8. view->setModel(model);
9. view->show();
10. }
1. #include <QSqlQueryModel>
2. #include <QTableView>
1. int column = model->columnCount(); //获得列数
2. int row = model->rowCount(); // 获得行数
3. QSqlRecord record = model->record(1); //获得一条记录
4. QModelIndex index = model->index(1,1); //获得一条记录的一个属性的值
5. qDebug() << “column num is:” << column << endl
6. << “row num is:” << row << endl
7. <<”the second record is:” << record << endl
8. << “the data of index(1,1) is:”<< index.data();
1. #include <QSqlRecord>
2. #include <QModelIndex>
3. #include <QDebug>
1. QSqlQuery query = model->query();
2. query.exec(“select name from student where id = 2 “);
3. query.next();
4. qDebug() << query.value(0).toString();
1. void Widget::on_pushButton_clicked()
2. {
3. QSqlQueryModel *model = new QSqlQueryModel;
4. model->setQuery(“select * from student”);
5. model->setHeaderData(0, Qt::Horizontal, tr(“id”));
6. model->setHeaderData(1, Qt::Horizontal, tr(“name”));
7. QTableView *view = new QTableView;
8. view->setModel(model);
9. view->show();
10.
11. QSqlQuery query = model->query();
12. query.exec(“insert into student values (10,’yafei10′)”);
13. //插入一条记录
14. }
1. void Widget::on_pushButton_clicked()
2. {
3. QSqlQueryModel *model = new QSqlQueryModel;
4. model->setQuery(“select * from student”);
5. model->setHeaderData(0, Qt::Horizontal, tr(“id”));
6. model->setHeaderData(1, Qt::Horizontal, tr(“name”));
7. QTableView *view = new QTableView;
8. view->setModel(model);
9. view->show();
10. QSqlQuery query = model->query();
11. query.exec(“insert into student values (20,’yafei20′)”);
12. //插入一条记录
13. model->setQuery(“select * from student”); //再次查询整张表
14. view->show(); //再次进行显示,这句也可以不写
15. }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。