SQLite3

文章目录

  • [SQLite3 C/C++API介绍](#SQLite3 C/C++API介绍)
  • [SQLite3 C/C++ API 使⽤](#SQLite3 C/C++ API 使⽤)

SQLite3 C/C++API介绍

C/C++ API是SQLite3数据库的⼀个客⼾端,提供⼀种⽤C/C++操作数据库的⽅法。

SQLite3 C/C++ API 使⽤

下⾯我们将这⼏个接⼝封装成⼀个类,快速上⼿这⼏个接口

  1. 创建/打开数据库文件
  2. 针对打开的数据库执行操作
    1. 表的操作
    2. 数据的操作
  3. 关闭数据库
cpp 复制代码
#include <iostream>
#include <string>
#include <sqlite3.h>
using namespace std;

class SqliteHelper 
{
public:
    typedef int(*SqliteCallback)(void*,int,char**,char**); //回调函数指针
    SqliteHelper(const string &dbfile) : _dbfile(dbfile), _handler(nullptr){}
    
    bool open(int safe_leve = SQLITE_OPEN_FULLMUTEX) //串行化模式
    {
        //int sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs );
        int ret = sqlite3_open_v2(_dbfile.c_str(), &_handler, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | safe_leve, nullptr);
        if (ret != SQLITE_OK) {
            cout << "创建/打开sqlite数据库失败: ";
            cout << sqlite3_errmsg(_handler) << endl;
            return false;
        }
        return true;
    }

    bool exec(const string &sql, SqliteCallback cb, void *arg) //arg是cb回调函数的参数
    {
        //int sqlite3_exec(sqlite3*, char *sql, int (*callback)(void*,int,char**,char**), void* arg, char **err)
        int ret = sqlite3_exec(_handler, sql.c_str(), cb, arg, nullptr);
        if (ret != SQLITE_OK) 
        {
            cout << sql << endl;
            cout << "执行语句失败: ";
            cout << sqlite3_errmsg(_handler) << endl;
            return false;
        }
        return true;
    }
    void close() 
    {
        //int sqlite3_close_v2(sqlite3*);
        if (_handler) sqlite3_close_v2(_handler);
    }
private:
    string _dbfile;
    sqlite3 *_handler;
};
相关推荐
qq_413502021 小时前
如何创建CDB公共用户_C##前缀强制规则与CONTAINER=ALL
jvm·数据库·python
yexuhgu2 小时前
CSS如何利用-checked实现纯CSS手风琴折叠_通过状态选择器控制区域高度
jvm·数据库·python
2301_779622412 小时前
mysql如何通过主从备份实现读写分离_配置mysql架构模式
jvm·数据库·python
m0_741173333 小时前
HTML5中WebSocket在弱网环境下的延迟抖动算法补偿
jvm·数据库·python
2401_871492853 小时前
Pandas如何做时间差对齐_pd.merge_asof按最近的时间戳合并两表
jvm·数据库·python
2403_883261094 小时前
如何用 nodeType 与 nodeName 准确判断当前节点的物理类型
jvm·数据库·python
qq_413502024 小时前
如何利用 Block Tree 避免不必要的子组件重渲染?Vue3 编译黑科技
jvm·数据库·python
m0_624578594 小时前
CSS定位如何实现多行文字垂直居中_通过绝对定位模拟表格
jvm·数据库·python
dfdfadffa4 小时前
mysql如何排查网络延迟引起的数据库连接问题_使用ping测试
jvm·数据库·python
2303_821287385 小时前
JavaScript中Redux-Thunk处理异步Action的任务流
jvm·数据库·python