SQLite3数据库连接查询(c++篇)

简介

SQLite3作为一个轻量级数据库引擎,拥有无服务器,无需外部依赖,可夸平台等特性。

将SQLite与项目结合

1,将 源码文件 导入到项目代码中:

由于SQLite是开源的,所以大家可以自行前往开源社区下载源码,或者在我的上传资源里下载;

sqlite3.c
sqlite3.h

2,连接数据库

函数:int sqlite3_open(const char zFilename,sqlite3 *ppDb)
功能:打开SQLite数据库
参数:
zFilename :数据库名称(包含路径)
ppDb :指向sqlite句柄的指针,后面对数据库所有的操作都要依赖这个句柄
返回值:成功返回0,失败返回错误码(非零)

void OpenDB()
{
    sqlite3* pSQLite = NULL;
    std::string strPath = "SI.db";
    int result = sqlite3_open(strPath .c_str(), &pSQLite);
    if (result == SQLITE_OK)
    {
        std::clog << "数据库连接成功"<<endl;
    }
    else {
        std::clog << "数据库连接失败"<<endl;
    }
}

3,查询数据库-方法1

函数:int sqlite3_get_table(sqlite3 db, const char sql, char resultp, int_nrow, int _ncolumn, char* errmsg);
功能:执行SQL操作 -- &#x4E0D;&#x4F7F;&#x7528;&#x56DE;&#x8C03;&#x51FD;&#x6570;
参数: db :数据库句柄 sql :SQL语句
resultp :用来指向sql执行结果的指针
nrow:满足 条件的记录的数目
ncolumn :每条记录包含的字段数目
errmsg :错误信息指针的地址
返回值 :成功返回0,失败返回错误码(非零)

void QueryDB(string strSQL)
{
    int iRt = 0;
    char * zErrMsg = NULL;
    char ** pResult = NULL;
    int nrow = 0;
    int ncolumn = 0;
    iRt = sqlite3_get_table(m_pSQLite, strSQL.c_str(), &pResult, &nrow, &ncolumn, &zErrMsg);
    if (iRt != SQLITE_OK)
    {
        printf("执行sql语句失败\n");
        return -1;
    }

    int iIndex = ncolumn;
    for (int i = 0; i < nrow; i++)
    {
        for (int j = 0; j < ncolumn; j++)
        {
            printf("%-8s : %-8s\n", pResult[j], pResult[iIndex]);
            iIndex++;
        }
        printf("***************************\n");
    }
    sqlite3_free_table(pResult);
}

4,查询数据库-方法2

函数:int sqlite3_exec(sqlite3 db, const char sql, sqlite3_callback callback, void , char *errmsg);
功能:执行SQL操作 – &#x4F7F;&#x7528;&#x56DE;&#x8C03;&#x51FD;&#x6570;
参数:
db :数据库句柄
sql :SQL语句,就是我们前面两章用于操作表的增删改查语句
callback:回调函数,每返回一条记录,则调用一次回调函数
errmsg :错误信息指针的地址 返回值:成功返回0,失败返回错误码
返回值:成功返回0,失败返回错误码


int callback(void *para, int f_num, char **f_val, char **f_name)
{
    for (int i = 0; i < f_num; i++)
    {
        printf("%-8s", f_val[i]);
    }
    printf("\n");
    return 0;
}

void QueryDB_1(string strSQL)
{
    int iRt = 0;
    char * zErrMsg = NULL;
    char ** pResult = NULL;
    int nrow = 0;
    int ncolumn = 0;
    iRt = sqlite3_exec(m_pSQLite, strSQL.c_str(), &callback, NULL, &zErrMsg);
    if (iRt != SQLITE_OK)
    {
        printf("执行sql语句失败\n");
    }
     printf("执行sql语句成功\n");
}

5,断开数据库连接

函数:int sqlite3_close(sqlite3 *db)
功能:执行SQL操作 – &#x4F7F;&#x7528;&#x56DE;&#x8C03;&#x51FD;&#x6570;
参数:
db :数据库句柄
返回值:成功返回0,失败返回错误码

void CloseDB()
{
    int iRt = sqlite3_close(m_pSQLite);
    if(iRt != SQLITE_OK)
    {
        printf("数据库连接断开失败\n");
    }
    printf("数据库连接断开成功\n");
}

Original: https://blog.csdn.net/weixin_43821643/article/details/125508383
Author: 修道-0323
Title: SQLite3数据库连接查询(c++篇)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/815102/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球