我是靠谱客的博主 酷炫小蝴蝶,这篇文章主要介绍QT5中使用SQLite的实现方法,现在分享给大家,希望可以做个参考。

SQLite(sql)是一款开源轻量级的数据库软件,不需要server,可以集成在其他软件中,非常适合嵌入式系统。
Qt5以上版本可以直接使用SQLite。

1、修改.pro文件,添加SQL模块:

复制代码
1
QT += sql

2、main.cpp代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "mainwindow.h" #include <QApplication> //添加头文件 #include <qdebug.h> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> int main(int argc, char *argv[]) { QApplication a(argc, argv); //建立并打开数据库 QSqlDatabase database; database = QSqlDatabase::addDatabase("QSQLITE"); database.setDatabaseName("MyDataBase.db"); if (!database.open()) { qDebug() << "Error: Failed to connect database." << database.lastError(); } else { qDebug() << "Succeed to connect database." ; } //创建表格 QSqlQuery sql_query; if(!sql_query.exec("create table student(id int primary key, name text, age int)")) { qDebug() << "Error: Fail to create table."<< sql_query.lastError(); } else { qDebug() << "Table created!"; } //插入数据 if(!sql_query.exec("INSERT INTO student VALUES(1, "Wang", 23)")) { qDebug() << sql_query.lastError(); } else { qDebug() << "inserted Wang!"; } if(!sql_query.exec("INSERT INTO student VALUES(2, "Li", 23)")) { qDebug() << sql_query.lastError(); } else { qDebug() << "inserted Li!"; } //修改数据 sql_query.exec("update student set name = "QT" where id = 1"); if(!sql_query.exec()) { qDebug() << sql_query.lastError(); } else { qDebug() << "updated!"; } //查询数据 sql_query.exec("select * from student"); if(!sql_query.exec()) { qDebug()<<sql_query.lastError(); } else { while(sql_query.next()) { int id = sql_query.value(0).toInt(); QString name = sql_query.value(1).toString(); int age = sql_query.value(2).toInt(); qDebug()<<QString("id:%1 name:%2 age:%3").arg(id).arg(name).arg(age); } } //删除数据 sql_query.exec("delete from student where id = 1"); if(!sql_query.exec()) { qDebug()<<sql_query.lastError(); } else { qDebug()<<"deleted!"; } //删除表格 sql_query.exec("drop table student"); if(sql_query.exec()) { qDebug() << sql_query.lastError(); } else { qDebug() << "table cleared"; } //关闭数据库 database.close(); return a.exec(); }

3、应用程序输出如下:

这里写图片描述

4、创建的 MyDataBase.db 在build的这个文件夹下:
D:QTprojectbuild-sl-Desktop_Qt_5_10_1_MinGW_32bit-Debug

到此这篇关于QT5中使用SQLite的实现方法的文章就介绍到这了,更多相关QT5使用SQLite内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是酷炫小蝴蝶最近收集整理的关于QT5中使用SQLite的实现方法的全部内容,更多相关QT5中使用SQLite内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部