QT5中使用SQLite的實現(xiàn)方法
SQLite(sql)是一款開源輕量級的數(shù)據(jù)庫軟件,不需要server,可以集成在其他軟件中,非常適合嵌入式系統(tǒng)。
Qt5以上版本可以直接使用SQLite。
1、修改.pro文件,添加SQL模塊:
QT += sql
2、main.cpp代碼如下:
#include "mainwindow.h"
#include <QApplication>
//添加頭文件
#include <qdebug.h>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//建立并打開數(shù)據(jù)庫
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." ;
}
//創(chuàng)建表格
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!";
}
//插入數(shù)據(jù)
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!";
}
//修改數(shù)據(jù)
sql_query.exec("update student set name = \"QT\" where id = 1");
if(!sql_query.exec())
{
qDebug() << sql_query.lastError();
}
else
{
qDebug() << "updated!";
}
//查詢數(shù)據(jù)
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);
}
}
//刪除數(shù)據(jù)
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";
}
//關(guān)閉數(shù)據(jù)庫
database.close();
return a.exec();
}
3、應用程序輸出如下:

4、創(chuàng)建的 MyDataBase.db 在build的這個文件夾下:
D:\QT\project\build-sl-Desktop_Qt_5_10_1_MinGW_32bit-Debug
到此這篇關(guān)于QT5中使用SQLite的實現(xiàn)方法的文章就介紹到這了,更多相關(guān)QT5使用SQLite內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VS Code 中搭建 Qt 開發(fā)環(huán)境方案分享
這篇文章主要介紹了VS Code 中搭建 Qt 開發(fā)環(huán)境方案分享的相關(guān)資料,需要的朋友可以參考下2022-12-12
C++如何通過ostringstream實現(xiàn)任意類型轉(zhuǎn)string
再使用整型轉(zhuǎn)string的時候感覺有點棘手,因為itoa不是標準C里面的,而且即便是有itoa,其他類型轉(zhuǎn)string不是很方便。后來去網(wǎng)上找了一下,發(fā)現(xiàn)有一個好方法2013-09-09
C語言中的結(jié)構(gòu)體內(nèi)嵌函數(shù)用法
這篇文章主要介紹了C語言中的結(jié)構(gòu)體內(nèi)嵌函數(shù)用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
Qt 使用Poppler實現(xiàn)pdf閱讀器的示例代碼
下面小編就為大家分享一篇Qt 使用Poppler實現(xiàn)pdf閱讀器的示例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01

