(一)sqlite的安装

一、直接用命令安装(需要linux联网)

sudo apt-get update
sudo apt-get install sqlite3

二、直接编译源码

1、将源码拷贝到Ubuntu的非共享目录解压
源码下载:

链接:https://pan.baidu.com/s/16ZWcXpFzMwW9nBq6dVWs9w
提取码:5r9e

解压命令:tar -xzvf sqlite-snapshot-201708031550.tar.gz
在这里插入图片描述

2、直接编译源码
(1)配置

cd sqlite-snapshot-201708031550
./configure --prefix=/home/gec/sqlite

在这里插入图片描述
(2)编译

make

(3)安装

make install

安装完成之后sqlite3的可执行文件就会出现在/home/gec/sqlite/bin目录中,如果要直接使用可以将该文件拷贝到 /usr/bin目录下。
在这里插入图片描述在这里插入图片描述

(二)sqlite的使用

(1)新建一个数据库文件

sqlite3 数据库文件路径 //打开/创建
//比如:sqlite3 first.db
//打开数据库进入命令行

在这里插入图片描述

(2)基本操作命令

.exit/.quit ------ 退出数据库命令行
.help ------ 帮助说明信息
.tables ----查看当前数据库中所有的表

(3)数据库访问的SQL语句

基本语法:
所有的SQL语句都以分号(;)结束,不区分大小写

1)新建表格

create table 表名(字段名1 字段类型1,字段名2 字段类型2,字段名3 字段类型3....);
比如:
//创建一个stutbl的表,表中有三个字段
//分别是整数类型的学号id,字符串类型的name,整数类型的age
create table stutbl(id int,name char[20],age int);
//不存在则创建
create table if not exists stutbl(id int,name char[20],age int);

//如果希望表中的某个字段的内容不重复,可以用unique修饰该字段
create table if not exists stutbl(id int unique,name char[20],age int);

2)删除表格

drop table 表名;

3)往表格中插入数据

insert into 表名 values(字段值1,字段值2,字段值3....);
//字段值如果是字符串,必须用''(单引号)括起来
比如:
    insert into stutbl values(1,'张飞',23);
    insert into stutbl values(2,'赵云',19);
    insert into stutbl values(3,'刘备',31);

完成插入之后,stutbl的表格内容如下:
在这里插入图片描述

4)查询表中的数据

//查询表中的所有数据
select * from 表名;

4)按条件查找:

1.使用where指定查询条件
    select * from testtbl where class=6;//查找class值为6的条目
    select * from testtbl where score>=90 and score<=100;
2.查询指定的字段    
    select id,name,score from testtbl;//只查询id,name和score
3.使用where+like实现模糊查询
    select * from testtbl where name like '何%';//查找名字以何开头的条目 
4.使用order by实现查询结果按某个字段的值升序/降序输出
    select * from testtbl order by score desc;//按分数降序输出    
   select * from testtbl order by grade asc;//按年级升序输出   

5)删除表中的条目

delete from 表名 where 条件;//删除所有符合条件的条目
比如:
    delete from testtbl where id=1;

6)更新(修改)表中的条目

update 表名 set 字段名1=字段值1,字段名2=字段值2.... where 条件;//修改符合条件的条目
比如:
    update testtbl set age=17,score=83.5 where id=4;

(4)sqlite中数字段类型

数字:
int ---------- 整型
smallint ----- 短整型
tinyint ------ 微型整数(0~255)
bit ---------- 0 or 1
float ------ 单精度浮点型
real ------- 双精度浮点型

字符串:
char ------ 非unicode定长字符串 < 8000
varchar — 非unicode变长字符串 <8000
text ------ 非unicode变长字符串 < 2^32-1
nchar ------ unicode定长字符串 < 8000
nvarchar — unicode变长字符串 < 8000
ntext ------ unicode变长字符串 < 2^32-1

5.sqlite的C语言访问接口
sqlite本身自带C语言访问接口,在C语言环境下可以直接调用,使用这些接口的代码需要把 sqlite的源码编译进可执行程序 或者 编译时连接sqlite的库。
(1)打开 --------- sqlite3_open

int sqlite3_open(
  const char *filename,   /*数据库的文件路径*/
  sqlite3 **ppDb          /*输出参数:传出代表打开数据库的句柄*/
);
//成功返回SQLITE_OK,否则打开失败

(2)关闭 --------- sqlite3_close

int sqlite3_close(sqlite3 *pDb); //传入要关闭的数据库的句柄

编译方法(必须链接pthread库和dl库):

1.直接编译源码
    gcc sqlite3.c sqlite_test.c -pthread -ldl -o sqlite_test
2.链接sqlite3的库
    gcc sqlite_test.c -pthread -ldl -lsqlite3 -L /home/gec/sqlite/lib -o sqlite_test1
    
//如果运行时找不到sqlite3库,可以将编译出来的库文件拷贝到/usr/lib目录下(cp -r)    

(三)如何在QT中使用sqlite

1、直接将sqlite3的源码加入到Qt工程中,在Qt代码中直接调用sqlite的接口
2、数据库查询结果显示到QT界面
Qt中提供的显示表格的类 --------- QTableView
QTableView在显示表格内容时,可以先把显示的内容写入到QStandardItemModel模型对象中,再将模型对象和表格对象绑定,绑定后模型的内容就会同步显示到表格中。
在这里插入图片描述
1)如何绑定表格和模型

QTableView的成员函数:
setModel(模型对象);

2)如何设置模型的内容

QStandardItemModel的成员函数:
设置列头部标题 ----- setHorizontalHeaderItem(列, QStandardItem *item);
设置单元格的内容 — setItem(行, 列, QStandardItem *item);
删除指定的行 ------ removeRows(起始行号,行数);
获取行数 ------- rowCount();

3、QT的数据库模块
Qt的开发环境集成了数据库访问的功能,也自带数据库sqlite,同时还提供了多种访问数据库的类,通过这些类可以实现对数据库的访问,使用Qt的数据库模块需要在工程文件中添加

QT += sql

(1)数据库驱动类 ------ QSqlDatabase
1)addDatabase ------- 添加数据库驱动

[static] QSqlDatabase QSqlDatabase::addDatabase(const QString &type, 
        const QString &connectionName = QLatin1String(defaultConnection));
//需要传入添加数据库的类型,比如使用sqlite就传 "QSQLITE"
//返回本类型对象

2)setDatabaseName ------- 设置数据库文件路径

void QSqlDatabase::setDatabaseName(const QString &name);
//传入数据库文件路径,添加数据库驱动成功之后才调用该函数

3)open ------- 打开数据库

bool QSqlDatabase::open();
//设置数据库文件路径后才能打开,返回成功/失败 

(2)执行SQL语句的类 -------- QSqlQuery
该类用于执行sql语句,可以直接使用sql语句构造,此时sql语句会自动执行一次。在构建QSqlQuery对象时必须保证数据库已经打开。
成员函数:
1)exec ------- 执行sql语句

bool QSqlQuery::exec(const QString &query);
//传入要执行的sql语句(不需要加分号),不传参数就执行构造时的sql语句
//返回执行成功/失败

2)lastError ------ 获取错误原因

QSqlError QSqlQuery::lastError() const;

3)next ------- 获取sql语句执行的结果(查询)

bool QSqlQuery::next();
//每调用一次返回一条结果,返回的结果在对象的value数组中,通过value成员函数获取
//数据全部取完返回false,否则返回true
QVariant QSqlQuery::value(int index) const;//通过编号获取字段值
QVariant QSqlQuery::value(const QString &name) const;//通过字段名获取字段值

最后附上一个例子实现建表、插入、查询、删除、修改、显示的操作。
stu.h

#ifndef STU_H
#define STU_H

#include <QWidget>
#include "sqlite3.h"
#include <QStandardItemModel>
namespace Ui {
class stu;
}

class stu : public QWidget
{
    Q_OBJECT

public:
    explicit stu(QWidget *parent = NULL);
    ~stu();
    //模型
    QStandardItemModel *model;
    //记录第几行
    quint16 count;

private slots:
    void on_pushButton_CreateTable_clicked();

    void on_pushButton_Insert_clicked();

    void on_lineEdit_InsertName_textEdited(const QString &arg1);

    void on_pushButton_Search_clicked();

    void on_pushButton_Delete_clicked();

    void on_pushButton_Update_clicked();

private:
    Ui::stu *ui;
    //数据库句柄
    sqlite3 *pDb;

};

#endif // STU_H

stu.cpp

#include "stu.h"
#include "ui_stu.h"
#include <QMessageBox>
#include <QDebug>

stu::stu(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::stu)
{
    ui->setupUi(this);

    //初始化模型
    model = new QStandardItemModel(this);
    model->setHorizontalHeaderItem(0, new QStandardItem("id"));
    model->setHorizontalHeaderItem(1, new QStandardItem("name"));
    model->setHorizontalHeaderItem(2, new QStandardItem("age"));

    //绑定模型和表格
    ui->tableView->setModel(model);
    //打开数据库
    int res = sqlite3_open("stu.db", &pDb);
    if(res != SQLITE_OK)
    {
        QMessageBox::warning(this,"提示", "打开数据库失败!");
    }
}

stu::~stu()
{
    delete ui;
    //关闭数据库
    sqlite3_close(pDb);
}

//建表
void stu::on_pushButton_CreateTable_clicked()
{
    QString sql = QString("create table if not exists %1(id int unique, name nvarchar, age int);")
            .arg(ui->lineEdit_TableName->text());
    //执行sql
    int res = sqlite3_exec(pDb, sql.toStdString().c_str(), NULL, NULL, NULL);
    if(res != SQLITE_OK)
    {
        QMessageBox::warning(this,"提示", "建表失败!");
        return;
    }

    //表名输入框和按钮禁止
    ui->lineEdit_TableName->setEnabled(false);
    ui->pushButton_CreateTable->setEnabled(false);

}

//插入
void stu::on_pushButton_Insert_clicked()
{
    QString sql = QString("insert into %1 values(%2,'%3',%4);")
            .arg(ui->lineEdit_TableName->text())
            .arg(ui->spinBox_Insertid->value())
            .arg(ui->lineEdit_InsertName->text())
            .arg(ui->spinBox_Insertage->value());
    //执行sql
    int res = sqlite3_exec(pDb, sql.toStdString().c_str(), NULL, NULL, NULL);
    if(res != SQLITE_OK)
    {
        QMessageBox::warning(this,"提示", "插入失败!");
    }
    //更新显示
    on_pushButton_Search_clicked();
}

void stu::on_lineEdit_InsertName_textEdited(const QString &arg1)
{
    if(arg1.isEmpty())
    {
        ui->pushButton_Insert->setEnabled(false);
    }
    else {
        ui->pushButton_Insert->setEnabled(true);
    }
}

//查询回调函数
static int sql_callback(void *arg, int col, char **str, char **name)
{
    //恢复对象的类型
    stu *db = static_cast<stu *>(arg);
    for(int i=0;i<col;i++)
    {
        //将查询结果显示到模型中
        db->model->setItem(db->count, i, new QStandardItem(str[i]));
    }
    db->count++;
    return SQLITE_OK;
}

//查询
void stu::on_pushButton_Search_clicked()
{
    QString sql = QString("select *from %1").arg(ui->lineEdit_TableName->text());
    count=0;
    //执行sql----把本对象传给回调函数
    int res = sqlite3_exec(pDb, sql.toStdString().c_str(), sql_callback, this, NULL);
    if(res != SQLITE_OK)
    {
        QMessageBox::warning(this,"提示", "查询失败!");
    }
}

//删除
void stu::on_pushButton_Delete_clicked()
{
    QString sql = QString("delete from %1 where id=%2;")
            .arg(ui->lineEdit_TableName->text())
            .arg(ui->spinBox_Deleteid->value());
    //执行sql
    int res = sqlite3_exec(pDb, sql.toStdString().c_str(), NULL, NULL, NULL);
    if(res != SQLITE_OK)
    {
        QMessageBox::warning(this,"提示", "删除失败!");
        return;
    }
    QMessageBox::warning(this,"提示", "删除成功!");
    //删除之前的内容
    model->removeRows(0,model->rowCount());
    //更新显示
    on_pushButton_Search_clicked();
}

//修改
void stu::on_pushButton_Update_clicked()
{
    QString sql;
    if(ui->radioButton_newid->isChecked())
    {
        sql = QString("update %1 set id=%2 where id=%3;")
                .arg(ui->lineEdit_TableName->text())
                .arg(ui->spinBox_newid->value())
                .arg(ui->spinBox_Updateid->value());
    }
    else if(ui->radioButton_newname->isChecked())
    {
        sql = QString("update %1 set name='%2' where id=%3;")
                .arg(ui->lineEdit_TableName->text())
                .arg(ui->lineEdit_newname->text())
                .arg(ui->spinBox_Updateid->value());
    }
    else if(ui->radioButton_newage->isChecked())
    {
        sql = QString("update %1 set age=%2 where id=%3;")
                .arg(ui->lineEdit_TableName->text())
                .arg(ui->spinBox_newage->value())
                .arg(ui->spinBox_Updateid->value());
    }
    //执行sql
    int res = sqlite3_exec(pDb, sql.toStdString().c_str(), NULL, NULL, NULL);
    if(res != SQLITE_OK)
    {
        QMessageBox::warning(this,"提示", "更新失败!");
        return;
    }
    QMessageBox::warning(this,"提示", "更新成功!");
    //更新显示
    on_pushButton_Search_clicked();
}

结果显示:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐