当前位置:网站首页>QT -- 1. QT connection database
QT -- 1. QT connection database
2022-07-01 07:42:00 【xuechanba】
Video tutorial Links :https://www.bilibili.com/video/BV1Li4y1f7ho?p=3.
class QSqlDatabase

The static member function in the above figure addDatabase The first parameter of type It indicates what type of database I want to connect to , Or what database software I'm connected to . The second parameter is the default parameter , Never mind .
class QSqlDatabase Common interface of


The function above setDatabaseName and removeDatabase The parameter of is to open or close the database file path .
The next step starts at QT Software to operate .
First, add the header file #include <QSqlDatabase>( Here it is main.cpp in )
As you can see from the figure, there is a yellow line under the header file and it shows that there is no such file or directory . Then why is it like this ?
It's about understanding QT The architecture of , Its whole framework is divided into modules . We usually use two modules , Namely Qt Core and QT GUI modular .
and QSqlDatabase It belongs to Qt SQL Of this module . So add this module to the project . How to add it ? We need to work on the project xxx.pro Add a sentence to the file .
QT += sql
As shown in the figure below .
here , And then main.c Middle view .
This indicates that the addition was successful .
Next , To create a QSqlDatabase The object of , But it cannot be created by a constructor , You need to use static functions addDatabase To create Sqlite3 Database connection .
The code is as follows :
// Create a QSqlDatabase The object of
// But it cannot be created by a constructor , You need to use static functions
// establish Sqlite3 Database connection
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
after , Specify which database file to open , Look at the code .
// Specify which database file to open ( Fill in the path of the database file )
db.setDatabaseName("/home/chantui/work/code/sqlite3Pro/stu.db");
// Judge whether the opening is successful
if(db.open()==false)
{
qDebug()<<" Open the failure ";
}
If the database file of the specified path does not exist , Will automatically create a .
If you want to create it under the current project directory , You do not need to specify a path , Just write the file name .
db.setDatabaseName("stu.db");
Last , When we finish operating the database , And shut down the database , The code is as follows .
db.close();
db.removeDatabase("/home/chantui/work/code/sqlite3Pro/stu.db");
The code screenshot is as follows :
Run code , Let's look at the effect . Go to the project directory ( Select the directory where you specify the builder ),
Encapsulate the work of connecting to the database

The singleton pattern
Picture content source link : https://www.runoob.com/design-pattern/singleton-pattern.html.
( Back of figure above , There is also a section on the implementation of the singleton pattern , You can adjust the past through the link to see , Since the focus of this chapter is not on the singleton mode , So don't go further here , If you have to distinguish between the implementation of the singleton pattern in this section , Should belong to the lazy type , Threads are not supported , Is the most basic implementation of singleton mode .)
good , Let's implement .
First , Create a file ,
The class name here is DBHelper ( Take at will ),
And then click next , Until completion , When it's done , open DPHelper.h file
#ifndef DBHELPER_H
#define DBHELPER_H
#include <QSqlDatabase>
class DBHelper
{
public:
// Open a... To the outside world “ Get the only available object ” Member function of
static DBHelper* getInstance();
private:
// Create a QSqlDatabase The object of db, After that, you need to db Object to initialize
QSqlDatabase db;
static DBHelper* Instance ;
// Because it's singleton mode , So let the constructor be private, In this way, the class will not be instantiated
DBHelper();
};
#endif // DBHELPER_H
stay DPHelper.cpp in ,
#include "DBHelper.h"
DBHelper* DBHelper::Instance=0;
DBHelper* DBHelper::getInstance()
{
if(Instance==0)
Instance =new DBHelper();
return Instance;
}
DBHelper::DBHelper()
{
// In the constructor, right db Object to initialize
db = QSqlDatabase::addDatabase("QSQLITE");
}
void DBHelper::createConnection()
{
// We need to specify the database file
db.setDatabaseName("tec.db");
db.open();
}
void DBHelper::destoryConnection()
{
db.close();
db.removeDatabase("stu.db");
}
In this way, the singleton is implemented .
that , In this singleton process , We also hope to solve this problem through the object of a singleton db Object to create database files 、 Open database file and close database file . So we need to DPHelper Class, and then provide relevant interfaces .
stay main.cpp in , Let's first include the header file we created for this class #include “DBHelper.h”.
then , Call the interface to connect and disconnect the database .
#include "mainwindow.h"
#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include "DBHelper.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DBHelper* helper = DBHelper::getInstance();
helper->createConnection();
helper->destoryConnection();
MainWindow w;
w.show();
return a.exec();
}
Run code , As shown in the figure below , Database files tec.db It's created .
边栏推荐
- [chapter 72 of the flutter problem series] a solution to the problem that pictures taken in the flutter using the camera plug-in are stretched
- 2022电工(中级)复训题库及答案
- 2022广东省安全员A证第三批(主要负责人)特种作业证考试题库模拟考试平台操作
- Caesar
- Understanding of Turing test and Chinese Room
- 下载Xshell和Xftp
- Wang Yingqi, founder of ones, talks to fortune (Chinese version): is there any excellent software in China?
- 三极管是一项伟大的发明
- base64
- 2022 test question bank and simulation test of tea master (primary) operation certificate
猜你喜欢

Inftnews | from "avalanche" to Baidu "xirang", 16 major events of the meta universe in 30 years

Operation and maintenance management system, humanized operation experience

2022年茶艺师(中级)复训题库及答案

Are there any practical skills for operation and maintenance management

Microsoft announces open source (Godel) language model chat robot
![[MySQL learning notes 25] SQL statement optimization](/img/01/cf0556961670bb43512caab8d5f4e5.png)
[MySQL learning notes 25] SQL statement optimization

【深圳IO】精确食品称(汇编语言的一些理解)
![[lingo] solve quadratic programming](/img/4d/3f7de69943f29a71c4039299c547f7.png)
[lingo] solve quadratic programming

继妹变继母,儿子与自己断绝关系,世界首富马斯克,为何这么惨?

ctfshow-web355,356(SSRF)
随机推荐
Which securities company is better or safer for mobile phone account opening
Saving db4i depth camera pictures with MATLAB
十大劵商如何开户?另外,手机开户安全么?
Eigen矩阵运算库快速上手
2022 test question bank and simulation test of tea master (primary) operation certificate
C language implementation [Sanzi chess game] (step analysis and implementation source code)
The computer has a network, but all browser pages can't be opened. What's the matter?
Redisson uses the full solution - redisson official document + comments (Part 2)
[Shenzhen IO] precise Food Scale (some understanding of assembly language)
华泰证券开户是安全可靠的么?怎么开华泰证券账户
【微服务|openfeign】Feign的日志记录
C# Newtonsoft. Use of job in JSON
2022 Guangdong Provincial Safety Officer a certificate third batch (main person in charge) special operation certificate examination question bank simulated examination platform operation
Apple account password auto fill
atguigu----脚手架--02-使用脚手架(2)
Is it safe and reliable for Huatai Securities to open an account? How to open Huatai Securities Account
[MySQL learning notes 28] storage function
Introduction to kubernetes resource objects and common commands (II)
浅谈CVPR2022的几个研究热点
Those high-frequency written tests and interview questions in [Jianzhi offer & Niuke 101] - linked list