<> use QSQL Database needs to be added

<>1. stay .Pro Add to file

<>2. Add the class header file to be used in the header file

<> Database all classes

<> Important classes and functions :

<>QSqlDatabase class

<>1. Connect to database

QSqlDatabase addDatabase(const QString &type, const QString &connectionName =
QLatin1String(defaultConnection)) This function is used to add our database to the connection list , parameter 1
: Indicates what type of database you are , such as sqlite Use it if you want QSQLITE parameter 2: Connection name , Indicates the name of the file connecting to the database , If there are multiple databases , You need to define it yourself
Return value : Is our database handle
<>2. Connect to remote host database

If it is not set, the default is to generate database files in the QT Under engineering documents

<>3. Set the port to connect to the host

<>4. Set database file name

Database file name is not a connection name , Database file must be in use Open Set before opening the database

<>5. Set the user name to use the database

<>6. Set password to use database

<>7. Open database

Directly use the account and password set above to open and use the first open,
Use the second password of his account open

<>8. Return database type

<>9. implement SQL sentence

<>QSqlQuery class

<> implement sql sentence

exec function
mode 1: Directly write the to be executed in the constructor sql sentence , Recall exec Function execution

Directly in the parameter const QString &query = QString() Write the sql sentence , Recall
exec() function
mode 2: Direct call , hold sql Statement is executed in a parameter

implement sql The result of the statement is saved in QSQLQuery Array of Value inside

next function
Next record in search results ( If available ), And locate the query on the retrieved record , This function is generally used to find

<> Display database data

Generally, we write the data into the data display model first , Then write the passing model into the table

<>QStandardItemModel Data display model
<>1. Set column header data ( Field name )

void setHorizontalHeaderItem(int column, QStandardItem *item) Parameter description : int column:
Which column QStandardItem*item: Field name is the name of the column <>2. Set a cell data

void setItem(int row, int column, QStandardItem *item) parameter : row: Which line column: That column
QStandardItem*item: Data value for example : model->setItem(count,0,newQStandardItem(sql_query.
value(0).toString())); <>3. How to write model data to QTableView
use QTableView Member function of setModel( Model object ) function

<>QTableView Table data display

use QTableView Member function of setModel( Model object ) function , Set the data model to QTableView Displayed model

<> Test code
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QSql
> #include <QSqlDatabase> #include<QSqlDriver> #include<QDebug> #include<
QSqlQuery> #include<QSqlError> #include<QString> #include <QStandardItemModel>
QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class
MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent =
nullptr); ~MainWindow(); public: void sqlit3_init(); QSqlDatabase db;
QStandardItemModel*model; int count=0; void Init_model(); private slots: void
on_pushButton_3_clicked(); void on_insert_bt_clicked(); void
on_delect_bt_clicked(); void on_read_bt_clicked(); void on_modify_bt_clicked();
void on_select_bt_clicked(); private: Ui::MainWindow *ui; QSqlDatabase *db1; };
#endif // MAINWINDOW_H #include "mainwindow.h" #include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::
MainWindow) { ui->setupUi(this); sqlit3_init(); Init_model(); } MainWindow::~
MainWindow() { delete ui; db.close(); } void MainWindow::sqlit3_init() { db=
QSqlDatabase::addDatabase("QSQLITE");// Connect to database db.setDatabaseName("SQLITE.db");
// Database file name db.setUserName("root");// Set user name db.setPassword("root");// Set password // Print operation
qDebug()<<db.driverName(); qDebug()<<db.databaseName(); qDebug()<<db.password();
bool ok = db.open();// Open database file if (ok) { qDebug() << QString(" Database opened successfully "); } else {
qDebug() << " Database open failed !"; } } //1. Create table void MainWindow::on_pushButton_3_clicked() {
// db.setHostName("./SQLITE.db");// Set the host database to which you want to connect // db.setPort(6868);// Set port
QSqlQuery sql_query; if(! sql_query.exec("create table if not exists student
(id int primary key, name text,form text,length int,radius int)")) { qDebug() <<
"Error: Fail to create table." << sql_query.lastError(); } else { qDebug() <<
"Table created!"; } } //2. insert data void MainWindow::on_insert_bt_clicked() {
QSqlQuery sql_query; QString sql=QString( "insert into student values
(%1,'%2','%3',%4,%5);") .arg(ui->ID_edit->text().toInt()) .arg(ui->name_lineEdit
->text()) .arg(ui->form_lineEdit_2->text()) .arg(ui->length_lineEdit_3->text().
toInt()) .arg(ui->radius_lineEdit_4->text().toInt()); qDebug()<<sql; if(!
sql_query.exec(sql)) { qDebug()<<"insert error"<< sql_query.lastError(); } else
{ qDebug()<<"insert ok"; } on_read_bt_clicked();// Update data } //3. Read all data void
MainWindow::on_read_bt_clicked() { model->clear();// Clear data in table Init_model();
// Initialize the model again , Otherwise, after clearing the model above , The column title is gone count=0;// Every time from 0 Row query QSqlQuery sql_query; QString
select_sql= "select * from student order by id asc";// order by Field name +asc Incremental mode if
(!sql_query.exec(select_sql)) { qDebug()<<sql_query.lastError(); } else { while(
sql_query.next())// Judge whether the next query data is available { // int id =
sql_query.value(0).toInt();// Print the first column of a row // int age = sql_query.value(1).toInt();
// qDebug()<<QString("id:%1 age:%2").arg(id).arg(age); // adopt QTableview Table display data
model->setItem(count,0,new QStandardItem(sql_query.value(0).toString())); model
->setItem(count,1,new QStandardItem(sql_query.value(1).toString())); model->
setItem(count,2,new QStandardItem(sql_query.value(2).toString())); model->
setItem(count,3,new QStandardItem(sql_query.value(3).toString())); model->
setItem(count,4,new QStandardItem(sql_query.value(4).toString())); count++;
// Increasing the number of rows } } } //4. Delete data void MainWindow::on_delect_bt_clicked() { QSqlQuery
sql_query; QString delect_sql=QString( "delete from student where id=%1").arg(ui
->ID_edit->text().toInt());// According to the tool ID Delete data if(!sql_query.exec(delect_sql)) { qDebug
()<<"delect error"<< sql_query.lastError(); } else { qDebug()<<"delect succeful"
; } on_read_bt_clicked();// Update data in table } //5. Update data // Modify data void MainWindow::
on_modify_bt_clicked() { QSqlQuery modify_query; QString modify_sql=QString(
"UPDATE student set name='%1',form='%2',length=%3,radius=%4 WHERE id=%5;") .arg(
ui->name_lineEdit->text()) .arg(ui->form_lineEdit_2->text()) .arg(ui->
length_lineEdit_3->text().toInt()) .arg(ui->radius_lineEdit_4->text().toInt()) .
arg(ui->ID_edit->text().toInt()); if(!modify_query.exec(modify_sql)) { qDebug()
<<"modify error"<< modify_query.lastError(); } else { qDebug()<<"modify
succeful"; } on_read_bt_clicked();// Update data in table } //UPDATE students set age=20 WHERE
id=2; // basis ID Query data void MainWindow::on_select_bt_clicked() { model->clear();
// Clear data in table Init_model();// Initialize the model again , Otherwise, after clearing the model above , The column title is gone count=0;// Every time from 0 Row query
QSqlQuery sql_query; QString select_sql = QString("select *from student where
id=%1 ;").arg(ui->ID_edit->text().toInt()); if(!sql_query.exec(select_sql)) {
qDebug()<<sql_query.lastError(); } else { while(sql_query.next())// Judge whether the next query data is available
{ // adopt QTableview Table display data model->setItem(count,0,new QStandardItem(sql_query.value(
0).toString())); model->setItem(count,1,new QStandardItem(sql_query.value(1).
toString())); model->setItem(count,2,new QStandardItem(sql_query.value(2).
toString())); model->setItem(count,3,new QStandardItem(sql_query.value(3).
toString())); model->setItem(count,4,new QStandardItem(sql_query.value(4).
toString())); } } } // Initialize data model void MainWindow::Init_model() { model=new
QStandardItemModel(this); // Set column name model->setHorizontalHeaderItem(0,new
QStandardItem(" tool ID")); model->setHorizontalHeaderItem(1,new QStandardItem(
" Tool name ")); model->setHorizontalHeaderItem(2,new QStandardItem(" Processing form ")); model->
setHorizontalHeaderItem(3,new QStandardItem(" Tool length ")); model->
setHorizontalHeaderItem(4,new QStandardItem(" Tool radius ")); // Set data model to Qtableviwe ui->
tableView->setModel(model); }

©2019-2020 Toolsou All rights reserved,
C++ of string of compare usage MySQL Basics Commonly used sentence ( Add / delete / modify query )C Language of a Gobang game implementation QT5.9 Use of learning notes QSqlQuery Method of Qt Getting Started tutorial 【 Basic controls 】QCalendarWidget calendar control java Polymorphic array of web Front end signature plug-in _signature_pad Plug in implements electronic signature function centos7 install RabbitMqspringboot use redis Experiment 4 Automated test tools - software test