SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。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." 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."else
{
qDebug() "Table created!";
}
//插入数据
if(!sql_query.exec("INSERT INTO student VALUES(1, \"Wang\", 23)"))
{
qDebug() else
{
qDebug() "inserted Wang!";
}
if(!sql_query.exec("INSERT INTO student VALUES(2, \"Li\", 23)"))
{
qDebug() else
{
qDebug() "inserted Li!";
}
//修改数据
sql_query.exec("update student set name = \"QT\" where id = 1");
if(!sql_query.exec())
{
qDebug() 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-Debug
以上就是良许教程网为各位朋友分享的Linu系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !