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:\QT\project\build-sl-Desktop_Qt_5_10_1_MinGW_32bit-Debug
到此這篇關于QT5中使用SQLite的實現方法的文章就介紹到這了,更多相關QT5使用SQLite內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_41656968/article/details/80473137