T5中如何使用SQLite


SQLite是一款开源轻量级的数据软件,本文主要介绍了QT5中使用SQLite的实现方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

Qt5以上版本可以直接使用SQLite。

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

QT += sql

2、main.cpp代码如下:

#include "mainwindow.h"
#include
//添加头文件
#include
#include
#include
#include

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()<

3、应用程序输出如下:

4、创建的 MyDataBase.db 在build的这个文件夹下:

D:\QT\project\build-sl-Desktop_Qt_5_10_1_MinGW_32bit-Debu

本文地址:​​https://www.lsqlite手机inuxprobe.com/qt5-sqlite-method.html​​include翻译