Linux上sqlite的安装和使用方法以及在QT中如何使用sqlite&笔记总结

简介: Linux上sqlite的安装和使用方法以及在QT中如何使用sqlite&笔记总结

(一)sqlite的安装

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

sudo apt-get update

sudo apt-get install sqlite3


二、直接编译源码

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

源码下载:

解压命令: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();
}


结果显示:

目录
打赏
0
1
1
0
26
分享
相关文章
在Rocky Linux 9上安装JDK并配置环境变量!
本教程介绍在Rocky Linux 9上安装JDK并配置环境变量的完整步骤。首先更新系统,清理旧版本JDK相关包及残留文件,确保环境干净。接着搜索并安装所需版本的JDK(如OpenJDK 17),验证安装是否成功。然后查找JDK安装路径,配置全局环境变量`JAVA_HOME`和`PATH`,最后验证环境变量设置。按照此流程操作,可顺利完成Java开发环境搭建,支持多版本切换(如JDK 8/11/17)。生产环境请谨慎操作,避免影响现有服务。
84 21
YashanDB Linux客户端安装
本文详细介绍了YashanDB客户端在Linux系统中的安装、使用与卸载步骤。安装方法包括适用于所有Linux平台的脚本安装和专用于CentOS的rpm安装。脚本安装需解压软件包并配置环境变量,而rpm安装则需以root用户执行相关命令。此外,文章还说明了如何通过yasql连接YashanDB并进行数据库操作,以及两种安装方式对应的卸载方法,帮助用户顺利完成客户端的管理与维护。
Linux 手动安装快速部署 LNMP 环境实战
本文详细记录了在阿里云ECS上手动搭建LNMP环境的过程,系统选用Ubuntu 24.04。主要内容包括:1) 使用`apt`安装Nginx和MySQL,并更新软件源;2) 编译安装PHP 8.4.5,配置PHP-FPM及环境路径;3) 配置MySQL root用户密码;4) 调整Nginx支持PHP解析并测试整体环境。通过此过程,重现手动配置服务器的细节,帮助熟悉各组件的安装与协同工作。
Android调试终极指南:ADB安装+多设备连接+ANR日志抓取全流程解析,覆盖环境变量配置/多设备调试/ANR日志分析全流程,附Win/Mac/Linux三平台解决方案
ADB(Android Debug Bridge)是安卓开发中的重要工具,用于连接电脑与安卓设备,实现文件传输、应用管理、日志抓取等功能。本文介绍了 ADB 的基本概念、安装配置及常用命令。包括:1) 基本命令如 `adb version` 和 `adb devices`;2) 权限操作如 `adb root` 和 `adb shell`;3) APK 操作如安装、卸载应用;4) 文件传输如 `adb push` 和 `adb pull`;5) 日志记录如 `adb logcat`;6) 系统信息获取如屏幕截图和录屏。通过这些功能,用户可高效调试和管理安卓设备。
|
18天前
|
微服务2——MongoDB单机部署4——Linux系统中的安装启动和连接
本节主要介绍了在Linux系统中安装、启动和连接MongoDB的详细步骤。首先从官网下载MongoDB压缩包并解压至指定目录,接着创建数据和日志存储目录,并配置`mongod.conf`文件以设定日志路径、数据存储路径及绑定IP等参数。之后通过配置文件启动MongoDB服务,并使用`mongo`命令或Compass工具进行连接测试。此外,还提供了防火墙配置建议以及服务停止的两种方法:快速关闭(直接杀死进程)和标准关闭(通过客户端命令安全关闭)。最后补充了数据损坏时的修复操作,确保数据库的稳定运行。
50 0
Android数据存储:解释SQLite数据库在Android中的使用。
Android数据存储:解释SQLite数据库在Android中的使用。
113 0
在 Android Studio 中结合使用 SQLite 数据库实现简单的注册和登录功能
在 Android Studio 中结合使用 SQLite 数据库实现简单的注册和登录功能
326 2
48. 【Android教程】数据库:SQLite 的使用
48. 【Android教程】数据库:SQLite 的使用
181 1
Android之SQLite数据库使用详解
Android之SQLite数据库使用详解
在 Android Studio 中结合使用 SQLite 数据库实现简单的注册和登录功能
在 Android Studio 中结合使用 SQLite 数据库实现简单的注册和登录功能
302 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等