当前位置:网站首页>QT learning notes QtSql
QT learning notes QtSql
2022-07-29 06:13:00 【Q-Stark】
Catalog
Preface
Due to work needs , To implement a small data management system . Ben wanted to pick it up QT Skill ideas , Study QT Development interface management database operation .
One 、QtSQL brief introduction
QtSQL The module realizes the access to the database ,Qt SQL Three different levels of API For developers . Including driver layer ,SQL API layer , User interface layer .
| level | describe |
|---|---|
| Driver layer | The specific database and SQL The underlying bridging of interfaces , The support classes included are QSqlDriver、QSqlDriverCreator、QSqlDriverCreatorBase、QSqlDriverPlugin and QSqlResult |
| SQL API layer | QSqlDataBase Class provides a database access interface 、 Database connection operation ;QSqlQuery Class provides operations that interact with the database , Other support classes include QSqlError、QSqlField、QSqlTableModel and QSqlRecord |
| User interface layer | Provide mapping from database data to forms for data representation , The support classes included are QSqlQueryModel、QSqlTableModel and QSqlRelationalTableModel, These classes are based on Qt Model of / View structure design |
Using this module requires the following two steps :
- In the project file, that is pro Add the following line to the file
QT += sql
- Add the following line in the header file using this module
#include <QtSql>
Two 、SQLite brief introduction
There are many kinds of relational databases , Common is Oracle ORacle And Microsoft. SQL Server, And open source MySQL. These are a little extravagant and bloated when used in small database management .
Qt Provides an in-process database SQLite. No installation required , Lightweight . Views are also supported 、 Triggers and transactions , Support nested SQL function .
3、 ... and 、QtSQL Use
3.1 Establish a database connection
Before doing database operations , You must first establish a connection to the database . Database communication is usually distinguished by the connection name rather than the database name . We can establish multiple connections for the same database .QSqlDataBase Class supports creating default connections , It has no name . The following is a code to create and open the default connection
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("bigblue");
db.setDatabaseName("flightdb");
db.setUserName("acarlson");
db.setPassword("1uTbSbAs");
bool ok = db.open();
As shown in the code above , Creating a database connection only instantiates one QSqlDatabase Class object , If you want to use it, you have to call open Function to open it . Static functions addDatabase The prototype is as follows :
QSqlDatabase::addDatabase(
const QString &type,
const QString &connectionName = QLatin1String(defaultConnection)
)
Parameters type Is the driver name , You can specify which databases to connect to ; Parameters connectionname Is the above connection name , If not specified , Then use the default connection name , Later, you can directly use the correlation function without parameters .QT The supported drivers are as follows :
| Driver name | DBMS |
|---|---|
| QDB2 | IBM DB2 (version 7.1 and above) |
| QIBASE | Borland InterBase |
| QMYSQL | MySQL |
| QOCI | Oracle Call Interface Driver |
| QODBC | Open Database Connectivity (ODBC) - Microsoft SQL Server and other ODBC-compliant databases |
| QPSQL | PostgreSQL (versions 7.3 and above) |
| QSQLITE2 | SQLite version 2 |
| QSQLITE | SQLite version 3 |
After opening the database connection, we can operate the database through related functions , After using, you can close and remove the database through the following two functions
QSqlDatabase::close()
QSqlDatabase::removeDatabase()
3.2 perform SQL sentence
QSqlQuery Class provides an implementation SQL Statement and can traverse the returned result set of execution . After the database connection is established, you can use this class to execute the... Supported by the underlying database SQL sentence , All this method needs to do is create an instance object of this class , Then call the exec() function . as follows :
QSqlQuery query;
query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
3.1.1 Traversal result set
QSqlQuery Class provides an interface to get records , Calling exec After the function ,QSqlQuery The internal pointer of the class points to the position before the first record , We must call once QSqlQuery::next() Function to get the location of the first record . Then repeat the call next function , Until an error is returned .
while (query.next()) {
QString name = query.value(0).toString();
int salary = query.value(1).toInt();
qDebug() << name << salary;
}
QSqlQuery::value() Function returns a property value of the current record . Fields It's from 0 Index started . We can go through QSqlQuery::at() Get the row index of the current record , adopt QSqlQuery::size() Get the total number of records , That is, the number of lines .
QSqlQuery::value() The return value of QVariant type , This type can be converted to many C++ and core Qt data type , Such as int, QString, and QByteArray. Different database types are automatically mapped to similar Qt type .
QSQLITE SQLite version 3 Data Types
| QSQLITE SQLite version 3 data type | SQL type description | Recommended input (C++ or Qt data type) |
|---|---|---|
| NULL | NULL value. | NULL |
| INTEGER | Signed integer, stored in 8, 16, 24, 32, 48, or 64-bits depending on the magnitude of the value. | typedef qint8/16/32/64 |
| REAL | 64-bit floating point value. | By default mapping to QString |
| TEXT | Character string (UTF-8, UTF-16BE or UTF-16-LE). | Mapped to QString |
| CLOB | Character large string object | Mapped to QString |
| BLOB | The value is a BLOB of data, stored exactly as it was input. | Mapped to QByteArray |
3.1.2 increase 、 Update and delete records
QSqlQuery You can perform a variety of SQL sentence . More than select, Such as insert,update,delete.
1.insert
QSqlQuery query;
query.exec("INSERT INTO employee (id, name, salary) "
"VALUES (1001, 'Thad Beaumont', 65000)");
You can insert multiple records using placeholder operations ,Qt Two kinds of placeholder syntax are supported : Famous occupation and positioning occupation . Respectively
Famous occupation, i.e Oracle grammar
QSqlQuery query;
query.prepare("INSERT INTO employee (id, name, salary) "
"VALUES (:id, :name, :salary)");
query.bindValue(":id", 1001);
query.bindValue(":name", "Thad Beaumont");
query.bindValue(":salary", 65000);
query.exec();
Positioning space occupying means ODBC grammar
QSqlQuery query;
query.prepare("INSERT INTO employee (id, name, salary) "
"VALUES (?, ?, ?)");
query.addBindValue(1001);
query.addBindValue("Thad Beaumont");
query.addBindValue(65000);
query.exec();
2.update
QSqlQuery query;
query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");
3.delete
QSqlQuery query;
query.exec("DELETE FROM employee WHERE id = 1007");
3.1.3 The transaction operations
Transactions can be used to ensure that complex operations are atomic ( for example , Find foreign keys and create records ), Or provide a way to eliminate complex changes in the middle .
have access to QSQLDABASE::transaction() Start transaction , Then it is to be executed in the transaction context SQL command , And finally QSQLDABASE::commit() or QSQLDABASE::rollback().
When using transaction operations , The transaction must be started before chuangjie query . Examples are as follows :
QSqlDatabase::database().transaction();
QSqlQuery query;
query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
if (query.next()) {
int employeeId = query.value(0).toInt();
query.exec("INSERT INTO project (id, name, ownerid) "
"VALUES (201, 'Manhattan Project', "
+ QString::number(employeeId) + ')');
}
QSqlDatabase::database().commit();
3.3SQL Model class
Qt At the same time, three model classes are provided in the user interface layer to operate the database ,QSqlQueryModel、QSqlTableModel and QSqlRelationalTableModel. These three classes all inherit from QAbstractTableModel , Therefore, the data can be easily passed QListView and QTableView On display in UI In the interface ; In addition, based on the model / View structure , We can also easily change the data source without changing the code .
QSqlQueryModel
Provides a SQL Read only model of the query
QSqlQueryModel model;
model.setQuery("SELECT * FROM employee");
for (int i = 0; i < model.rowCount(); ++i) {
int id = model.record(i).value("id").toInt();
QString name = model.record(i).value("name").toString();
qDebug() << id << name;
}
QSqlTableModel
Provides a leaflet based SQL Read write model of table
QSqlTableModel model;
model.setTable("employee");
model.setFilter("salary > 50000");
model.setSort(2, Qt::DescendingOrder);
model.select();
for (int i = 0; i < model.rowCount(); ++i) {
QString name = model.record(i).value("name").toString();
int salary = model.record(i).value("salary").toInt();
qDebug() << name << salary;
}
Use the model , Can replace write SQL Statement to operate , If we can pass record() Or a row of records in the table , adopt setRecord() Modify the record . After all modifications on the model are completed , Use submitall perhaps submit To submit , Update the database .
for (int i = 0; i < model.rowCount(); ++i) {
QSqlRecord record = model.record(i);
double salary = record.value("salary").toInt();
salary *= 1.1;
record.setValue("salary", salary);
model.setRecord(i, record);
}
model.submitAll();
Set editing policy
The editing policy indicates whether the data modification made by the user in the view is fully applied to the database . The value range is
| Constant | value | describe |
|---|---|---|
| QSqlTableModel::OnFieldChange | 0 | All changes to the model will be immediately updated in the database |
| QSqlTableModel::OnRowChange | 1 | The modification of the current line takes effect when the user selects another different line |
| QSqlTableModel::OnManualSubmit | 2 | All modifications are temporarily stored in the model , Until the call submitAll() perhaps revertAll() |
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
QSqlRelationalTableModel
be based on QSqlTableModel An extension of , Support foreign keys .
3.4 Display data through views
QSqlQueryModel、QSqlTableModel and QSqlRelationalTableModel Classes can be used as data sources in Qt In the view class of , Such as QListView、QTableView and QTreeView And so on . among , The most common is QTableView, Because this view is most suitable for representing two-dimensional SQL Operating results .
If the model is readable and writable , The view will allow the user to edit fields , We can disable editing by calling .
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
We can use one model for multiple views , When the model is updated and edited in a view , The other views will update .
When using the insert row and delete row operations of the model , Special annotation will be made on the view , Until submission .
The view class can display a horizontal header and a vertical header . The horizontal header displays a column name above each column , By default , The column name is the field name of the database table , Can pass setHeaderData() Function to modify the column name . The vertical header displays the line number of each line on the leftmost side .
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("City"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("Country"));
Create a data aware form
At some point , We want to get and update the data of specific rows or columns in the database table through a form , You can use it QDataWidgetMapper class , For details, please refer to the official BOOKS Example . I haven't used this function yet .
边栏推荐
- 四、One-hot和损失函数的应用
- Chongqing Avenue cloud bank, as a representative of the software industry, was invited to participate in the signing ceremony of key projects in Yuzhong District
- Set automatic build in idea - change the code, and refresh the page without restarting the project
- 6、 Pointer meter recognition based on deep learning key points
- 入门到入魂:单片机如何利用TB6600高精度控制步进电机(42/57)
- Migration learning - geodesic flow kernel for unsupervised domain adaptation
- 基于msp430f2491的proteus仿真(实现流水灯)
- tensorflow中tf.get_variable()函数详解
- 基于wifi的温度采集与控制系统
- Error in installing pyspider under Windows: Please specify --curl dir=/path/to/build/libcurl solution
猜你喜欢

PyTorch的数据读取机制

The differences and reasons between MySQL with and without quotation marks when querying string types

Reading papers on fake news detection (2): semi supervised learning and graph neural networks for fake news detection

迁移学习——Transfer Joint Matching for Unsupervised Domain Adaptation

CV520国产替代Ci521 13.56MHz 非接触式读写器芯片

Transformer review + understanding

HAL学习笔记 - 7 定时器之高级定时器

华为云14天鸿蒙设备开发-Day1源码获取

Typical case of xdfs & Aerospace Institute HPC cluster

How to use the pre training language model
随机推荐
避坑:关于两个HC-05主从一体蓝牙模块互连,连不上问题
Transfer feature learning with joint distribution adaptation
逻辑回归-项目实战-信用卡检测任务(下)
PyTorch的数据读取机制
2、 During OCR training, txt files and picture data are converted to LMDB file format
C connect to SharePoint online webservice
ML11-SKlearn实现支持向量机
Am model in NLP field
基于DAC0832的直流电机控制系统
Wechat built-in browser prohibits caching
Hal learning notes - Basic timer of 7 timer
基于stm32的四针OLED显示
CS5340国产替代DP5340多比特音频 A/D 转换器
迁移学习——Transfer Joint Matching for Unsupervised Domain Adaptation
Model building in pytorch
Tf.get in tensorflow_ Detailed explanation of variable() function
物联网倾斜监测解决方案
Set automatic build in idea - change the code, and refresh the page without restarting the project
ML16 neural network (2)
二、深度学习数据增强方法汇总