当前位置:   article > 正文

sqlite数据库接口封装_sqlite3查询接口封装

sqlite3查询接口封装

头文件

#pragma once
#define SQLITE_HAS_CODEC

/*!
 * \file Sqlite.h
 * \date 2023/02/28 10:15
 *
 * \author 56389
 * Contact: user@company.com
 *
 * \brief 
 *
 * sqlite数据库访问
 *
 * \note
*/
#include "sqlite\sqlite3.h"
#include "CParamBind.h"
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <unordered_map>
#include <codecvt>
using std::map;
using std::vector;
using std::unordered_map;
using std::string;
using std::cout;
using std::endl;
typedef vector<std::map<std::string, std::string>> SqliteSelectResult;
class Sqlite
{
public:
    Sqlite(const std::string& strFileName);
    ~Sqlite();

    bool Exec(const std::string& sql);
    bool Query(const std::string& sql, SqliteSelectResult& selectResult);
    bool Begin();
    bool Commit();
    bool Vacuum();//数据库磁盘整理
public:
    bool Open();
    bool Close();
    static int select_cb(void* data, int cNum, char* column_values[], char* column_names[]);

public:
    static std::string utf8_to_gbk(const std::string& str);

    static std::string gbk_to_utf8(const std::string& str);
private:
    sqlite3* m_sqlite;
    std::string m_passwd;
    std::string dbFileName;
};

class SigleSqlite
{
public:
    ~SigleSqlite() { instance = nullptr; }

    static Sqlite* GetInstance()
    {
        if (instance == nullptr)
            instance = new Sqlite("xxxxxxx.db");
        return instance;
    }
    static void Destroy()
    {
        if (instance != nullptr)
        {
            delete instance;
        }
    }
private:
    static Sqlite* instance;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

cpp

#include <Windows.h>
#include "Sqlite.h"
#include "CGoogleLog.h"
#pragma comment(lib,"sqlite3_x64.lib")
Sqlite* SigleSqlite::instance = nullptr;
Sqlite::Sqlite(const std::string& strFileName)
{
    m_passwd = "20230427";
    dbFileName = strFileName;
    Open();
}
Sqlite::~Sqlite()
{
    //sqlite3_close(m_sqlite);
    Close();
}

bool Sqlite::Open()
{
    string errMsg = "";
    int ret = sqlite3_open(dbFileName.c_str(), &m_sqlite);
    if (SQLITE_OK == ret)
    {
        if (SQLITE_OK == sqlite3_key(m_sqlite, m_passwd.c_str(), m_passwd.size()))
        {
            LOG(INFO) << "sqlite3_key success!";
            return true;
        }
    }

    errMsg = sqlite3_errmsg(m_sqlite);
    LOG(FATAL) << "sqlite3_open error: " << errMsg;
    return false;
}

bool Sqlite::Exec(const std::string& sql)
{
   //LOG(INFO)<<sql;
   LOG(INFO) << utf8_to_gbk(sql);
    
    string errMsg = "";
    char* cerrMsg = nullptr;
    //string utf8Sql = TransCode::Asci2Utf8(sql);
    int ret = sqlite3_exec(m_sqlite, sql.c_str(), 0, 0, &cerrMsg);
    if (SQLITE_OK == ret)
    {
        return true;
    }

    errMsg = cerrMsg;
    sqlite3_free(cerrMsg);

    int retryTimes = 0;
    while (retryTimes < 5 && errMsg == "database is locked")
    {
        Sleep(100 * (retryTimes + 1));
        int ret = sqlite3_exec(m_sqlite, sql.c_str(), 0, 0, &cerrMsg);
        if (SQLITE_OK == ret)
        {
            errMsg = " retryTimes: " + std::to_string(retryTimes + 1);
            LOG(ERROR) << utf8_to_gbk(sql) << ": " << errMsg;
            return true;
        }
        errMsg = cerrMsg;
        sqlite3_free(cerrMsg);
        retryTimes++;
    }
    //LOG(ERROR) << utf8_to_gbk(sql) << ": " << errMsg;
    return false;
}

int Sqlite::select_cb(void* data, int cNum, char* column_values[], char* column_names[])
{
    SqliteSelectResult* selectResult = static_cast<SqliteSelectResult*>(data);
    map<string, string> record;
    for (int i = 0; i < cNum; i++)
    {
        if (column_values[i])
        {
            //record[column_names[i]] = TransCode::Utf82Asci(column_values[i]);
            record[column_names[i]] = column_values[i];
        }
        else
        {
            record[column_names[i]] = "NULL";
        }
    }
    selectResult->push_back(record);

    return 0;
}

std::string Sqlite::utf8_to_gbk(const std::string& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
    std::wstring tmp_wstr = conv.from_bytes(str);

    //GBK locale name in windows
    const char* GBK_LOCALE_NAME = ".936";

    std::wstring_convert<std::codecvt_byname<wchar_t, char, mbstate_t>> convert(new std::codecvt_byname<wchar_t, char, mbstate_t>(GBK_LOCALE_NAME));
    return convert.to_bytes(tmp_wstr);
}

std::string Sqlite::gbk_to_utf8(const std::string& str)
{
    //GBK locale name in windows
    const char* GBK_LOCALE_NAME = ".936";
    std::wstring_convert<std::codecvt_byname<wchar_t, char, mbstate_t>> convert(new std::codecvt_byname<wchar_t, char, mbstate_t>(GBK_LOCALE_NAME));
    std::wstring tmp_wstr = convert.from_bytes(str);

    std::wstring_convert<std::codecvt_utf8<wchar_t>> cv2;
    return cv2.to_bytes(tmp_wstr);
}

bool Sqlite::Query(const std::string& sql, SqliteSelectResult& selectResult)
{
    LOG(INFO) << sql;
    std::string errMsg = "";
    char* cerrMsg = nullptr;
    //string utf8Sql = TransCode::Asci2Utf8(sql);
    int ret = sqlite3_exec(m_sqlite, sql.c_str(), Sqlite::select_cb, (void*)&selectResult, &cerrMsg);
    if (SQLITE_OK == ret)
    {
        return true;
    }

    errMsg = cerrMsg;
    if (cerrMsg != nullptr)
    {
        sqlite3_free(cerrMsg);
    }

    int retryTimes = 0;
    while (retryTimes < 5 && errMsg == "database is locked")
    {
        Sleep(100 * (retryTimes + 1));
        int ret = sqlite3_exec(m_sqlite, sql.c_str(), Sqlite::select_cb, (void*)&selectResult, &cerrMsg);
        if (SQLITE_OK == ret)
        {
            errMsg = " retryTimes: " + std::to_string(retryTimes + 1);
            LOG(ERROR) << sql << ": " << errMsg;
            return true;
        }
        errMsg = cerrMsg;
        sqlite3_free(cerrMsg);
        retryTimes++;
    }
    LOG(ERROR) << sql << ": " << errMsg;
    return false;
}

bool Sqlite::Close()
{
    if (SQLITE_OK == sqlite3_close(m_sqlite))
    {
        LOG(INFO) << "sqlite3_close success";
        return true;
    }
    else
    {
        LOG(INFO) << "sqlite3_close failed";

        return false;
    }
}
bool Sqlite::Begin()
{
    std::string errMsg;
    char* cerrMsg = nullptr;
    int rc = sqlite3_exec(m_sqlite, "begin;", NULL, 0, &cerrMsg);
    if (rc != SQLITE_OK)
    {
        errMsg = cerrMsg;
        sqlite3_free(cerrMsg);
        LOG(ERROR) << "begin: " << errMsg;
        return false;
    }
    return true;
}

bool Sqlite::Commit()
{
    std::string errMsg;
    char* cerrMsg = nullptr;
    int rc = sqlite3_exec(m_sqlite, "commit;", NULL, 0, &cerrMsg);
    if (rc != SQLITE_OK)
    {
        errMsg = cerrMsg;
        sqlite3_free(cerrMsg);
        LOG(ERROR) << "commit: " << errMsg;
        return false;
    }
    return true;

    /* sqlite3_exec(m_sqlite, "commit;", NULL, 0, 0);*/
}

bool Sqlite::Vacuum()
{
    return Exec("VACUUM");
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203

sql绑定代码CParamBind.h

#pragma once
#ifndef __C_PARAM_BIND_H__
#define __C_PARAM_BIND_H__
#include <iostream>
#include <string>
using namespace std;
namespace ParamBind
{
    //************************************
// Method:    ReplaceSlot 绑定字符串参数到sql中
// FullName:  ReplaceSlot
// Access:    public
// Returns:   :type
// Qualifier:
// Parameter: std::string & strStateMent
// Parameter: T t
//************************************
    template <typename T>
    typename std::enable_if<std::is_same<char*, T>::value || std::is_same<const char*, T>::value>::type
        ReplaceSlot(std::string& strStateMent, T t)
    {
        int nPos = strStateMent.find_first_of('?');
        strStateMent.replace(nPos, 1, "'" + std::string(t) + "'");
    }

    //************************************
    // Method:    ReplaceSlot 绑定数值参数到sql中
    // FullName:  CMySql::ReplaceSlot
    // Access:    public
    // Returns:   :type
    // Qualifier:
    // Parameter: std::string & strStateMent
    // Parameter: T t
    //************************************
    template <typename T>
    typename  std::enable_if<std::is_integral<T>::value>::type ReplaceSlot(std::string& strStateMent, T t)
    {
        int nPos = strStateMent.find_first_of('?');
        std::string strValue = std::to_string(t);
        strStateMent.replace(nPos, 1, strValue);
    }

    //************************************
    // Method:    BindParams 参数递归展开终止
    // FullName:  CMySql::BindParams
    // Access:    public
    // Returns:   int
    // Qualifier:
    // Parameter: std::string & strStateMent
    //************************************
    inline int BindParams(std::string& strStateMent)
    {
        return 0;
    }

    //************************************
    // Method:    BindParams  递归展开不定长参数,同时进行值绑定
    // FullName:  CMySql::BindParams
    // Access:    public
    // Returns:   int
    // Qualifier:
    // Parameter: std::string & strStateMent
    // Parameter: T & & first
    // Parameter: Args & & ... args
    //************************************
    template <typename T, typename... Args>
    inline std::string BindParams(std::string& strStateMent, T&&  first, Args&&... args)
    {
        //参数展开时替换占位符
        string str1 = strStateMent;
        ReplaceSlot(str1, first);
        strStateMent = str1;
        BindParams(strStateMent, std::forward<Args>(args)...);
        std::string res = strStateMent;
        return res;
    }
}
#endif
**示例:
std::string sql = insert into table(?,?,?,?);
std::string sqlRes = BindParams(sql, "dfs",3, "df",5);**
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/480900
推荐阅读
相关标签
  

闽ICP备14008679号