• sqlite


    一、概述

      Sqlite 是一种轻量级的跨平台的开源数据库,设计目标是为嵌入式设备服务,它的处理速度比 Mysql、PostgreSQL 都快,而占用只有几百KB左右。除了支持基本的SQL语句,还支持事务处理。

    二、下载安装

      从官网 http://www.sqlite.org/download.html 可以下载源码包或自动编译包,如果在 Linux 下使用,可以下载 sqlite-autoconf-3080500.tar.gz ,解压后 ./configure && make && make install 即可;也可以下载源码包,里面只包含四个代码文件,比如在 cocos2d-x 项目中,就可以下载这个包添加进去即可使用。

    三、简单 Demo

    #include "sqlite3.h"
    #include <string>
    #include <stdio.h>
    
    using namespace std;
    
    int main()
    {
        sqlite3 *pdb = NULL;
    
        std::string path = "/root/test.db";
        int result = sqlite3_open(path.c_str(), &pdb);
        if (result == SQLITE_OK)
        {
            printf("connect mysqlite.db3 ok!");
            result = sqlite3_exec(pdb, "create table if not exists pet(id integer primary key autoincrement,name text,age integer)", NULL, NULL, NULL);
            if (result == SQLITE_OK)
            {
                printf("create table pet ok!");
                result = sqlite3_exec(pdb, "insert into pet(name,age) values('pet01','3');", NULL, NULL, NULL);
                if (result == SQLITE_OK)
                {
                    printf("insert table pet ok!");
                    char **ds;
                    int row, column;
                    result = sqlite3_get_table(pdb, "select * from pet", &ds, &row, &column, NULL);
                    printf("row=%d,column=%d", row, column);
                    for (int i = 0; i < row; i++)
                    {
                        std::string str = "";
                        for (int j = 0; j < column; j++)
                        {
                            str += ds[i*column + j];
                            str += "  ";
                        }
                        printf("%s", str.c_str());
                    }
                }
                else
                {
                    printf("insert table pet faild!");
                }
            }
            else
            {
                printf("create table pet faild! result:%d",result);
            }
        }
        else
        {
            printf("open database failed,  number%d", result);
        }
    }

    编译使用:g++ main.cpp -o main -lsqlite3

    四、相关工具

      Linux 下可以直接使用 sqlite3 命令行工具来操作 sqlite3 数据库文件,如 sqlite3 test.db;Windows 下可以使用 SqliteBrowser 图形化工具。

    五、操作函数封装

      默认提供的C版API写起来很麻烦,网上有各种语言版本的封装,这里推荐一个C++版本的:http://www.adp-gmbh.ch/sqlite/wrapper.html

      在 Linux 或其它非 Windows 环境下使用时,请删除 SQLiteWrapper.cpp 文件中的 #include <windows.h>,然后把所有使用 ::MessageBox 进行的日志输出改成相应平台的日志输出函数即可。另外,此版本存在内存泄露,没有任何地方调用 sqlite3_close 函数,这里我们手动在 SQLiteWrapper.h 文件中添加一个 bool Close(); 声明,然后在 SQLiteWrapper.cpp 文件中加上:

    bool SQLiteWrapper::Close() {
        if (db_)
        {
            if (sqlite3_close(db_) != SQLITE_OK) {
                return false;
            }
        }
        return true;
    }

    这里备份一下 cocos2d-x 下的修改后文件,方便以后直接使用:

    /*
    SQLiteWrapper.cpp
    
    Copyright (C) 2004 René Nyffenegger
    
    This source code is provided 'as-is', without any express or implied
    warranty. In no event will the author be held liable for any damages
    arising from the use of this software.
    
    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:
    
    1. The origin of this source code must not be misrepresented; you must not
    claim that you wrote the original source code. If you use this source code
    in a product, an acknowledgment in the product documentation would be
    appreciated but is not required.
    
    2. Altered source versions must be plainly marked as such, and must not be
    misrepresented as being the original source code.
    
    3. This notice may not be removed or altered from any source distribution.
    
    René Nyffenegger rene.nyffenegger@adp-gmbh.ch
    
    */
    
    #include "SQLiteWrapper.h"
    // TODO: raus
    //#include <windows.h>
    #include "cocos2d.h"
    USING_NS_CC;
    
    SQLiteWrapper::SQLiteWrapper() : db_(0) {
    }
    
    bool SQLiteWrapper::Open(std::string const& db_file) {
        if (sqlite3_open(db_file.c_str(), &db_) != SQLITE_OK) {
            return false;
        }
        return true;
    }
    
    bool SQLiteWrapper::Close() {
        if (db_)
        {
            if (sqlite3_close(db_) != SQLITE_OK) {
                return false;
            }
        }
        return true;
    }
    
    bool SQLiteWrapper::SelectStmt(std::string const& stmt, ResultTable& res) {
        char *errmsg;
        int   ret;
    
        res.reset();
    
        ret = sqlite3_exec(db_, stmt.c_str(), SelectCallback, static_cast<void*> (&res), &errmsg);
    
        if (ret != SQLITE_OK) {
            return false;
        }
        return true;
        //  if (ret != SQLITE_OK) {
        //    std::cout << stmt << " [" << errmsg << "]" << std::endl;
        //  }
    }
    
    // TODO parameter p_col_names
    int SQLiteWrapper::SelectCallback(void *p_data, int num_fields, char **p_fields, char** p_col_names) {
        ResultTable* res = reinterpret_cast<ResultTable*>(p_data);
    
        ResultRecord record;
    
    #ifdef SQLITE_WRAPPER_REPORT_COLUMN_NAMES
        // Hubert Castelain: column names in the first row of res if res is empty
    
        if (res->records_.size() == 0) {
            ResultRecord col_names;
    
            for (int i = 0; i < num_fields; i++) {
                if (p_fields[i]) col_names.fields_.push_back(p_col_names[i]);
                else
                    col_names.fields_.push_back("(null)"); // or what else ?
            }
            res->records_.push_back(col_names);
        }
    #endif
    
        for (int i = 0; i < num_fields; i++) {
            // Hubert Castelain: special treatment if null
            if (p_fields[i]) record.fields_.push_back(p_fields[i]);
            else             record.fields_.push_back("<null>");
        }
    
        res->records_.push_back(record);
    
        return 0;
    }
    
    SQLiteStatement* SQLiteWrapper::Statement(std::string const& statement) {
        SQLiteStatement* stmt;
        try {
            stmt = new SQLiteStatement(statement, db_);
            return stmt;
        }
        catch (const char* e) {
            return 0;
        }
    }
    
    SQLiteStatement::SQLiteStatement(std::string const& statement, sqlite3* db) {
        if (sqlite3_prepare(
            db,
            statement.c_str(),  // stmt
            -1,                  // If than zero, then stmt is read up to the first nul terminator
            &stmt_,
            0                   // Pointer to unused portion of stmt
            )
            != SQLITE_OK) {
            throw sqlite3_errmsg(db);
        }
    
        if (!stmt_) {
            throw "stmt_ is 0";
        }
    }
    
    SQLiteStatement::~SQLiteStatement() {
        // Hubert Castelain 28/8/2005
        // Prevent the database remaining locked after some statement.
        // syntax: int sqlite3_finalize(sqlite3_stmt *pStmt);
        if (stmt_) sqlite3_finalize(stmt_);
    }
    
    SQLiteStatement::SQLiteStatement() :
    stmt_(0)
    {
    }
    
    bool SQLiteStatement::Bind(int pos_zero_indexed, std::string const& value) {
        if (sqlite3_bind_text(
            stmt_,
            pos_zero_indexed + 1,  // Index of wildcard
            value.c_str(),
            value.length(),      // length of text
            SQLITE_TRANSIENT     // SQLITE_TRANSIENT: SQLite makes its own copy
            )
            != SQLITE_OK) {
            return false;
        }
        return true;
    }
    
    bool SQLiteStatement::Bind(int pos_zero_indexed, double value) {
        if (sqlite3_bind_double(
            stmt_,
            pos_zero_indexed + 1,  // Index of wildcard
            value
            )
            != SQLITE_OK) {
            return false;
        }
        return true;
    }
    
    bool SQLiteStatement::Bind(int pos_zero_indexed, int value) {
        if (sqlite3_bind_int(
            stmt_,
            pos_zero_indexed + 1,  // Index of wildcard
            value
            )
            != SQLITE_OK) {
            return false;
        }
        return true;
    }
    
    bool SQLiteStatement::BindNull(int pos_zero_indexed) {
        if (sqlite3_bind_null(
            stmt_,
            pos_zero_indexed + 1  // Index of wildcard
            )
            != SQLITE_OK) {
            return false;
        }
        return true;
    }
    
    bool SQLiteStatement::Execute() {
        int rc = sqlite3_step(stmt_);
        if (rc == SQLITE_BUSY) {
            //::MessageBox(0, "SQLITE_BUSY", 0, 0);
            CCLog("%s","SQLITE_BUSY");
            return false;
        }
        if (rc == SQLITE_ERROR) {
            //::MessageBox(0, "SQLITE_ERROR", 0, 0);
            CCLog("%s", "SQLITE_ERROR");
            return false;
        }
        if (rc == SQLITE_MISUSE) {
            //::MessageBox(0, "SQLITE_ERROR", 0, 0);
            CCLog("%s", "SQLITE_ERROR");
            return false;
        }
        if (rc != SQLITE_DONE) {
            //sqlite3_reset(stmt_);
            return false;
        }
        sqlite3_reset(stmt_);
        return true;
    }
    
    SQLiteStatement::dataType SQLiteStatement::DataType(int pos_zero_indexed) {
        return dataType(sqlite3_column_type(stmt_, pos_zero_indexed));
    }
    
    int SQLiteStatement::ValueInt(int pos_zero_indexed) {
        return sqlite3_column_int(stmt_, pos_zero_indexed);
    }
    
    std::string SQLiteStatement::ValueString(int pos_zero_indexed) {
        return std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt_, pos_zero_indexed)));
    }
    
    bool SQLiteStatement::RestartSelect() {
        sqlite3_reset(stmt_);
        return true;
    }
    
    bool SQLiteStatement::Reset() {
        int rc = sqlite3_step(stmt_);
    
        sqlite3_reset(stmt_);
    
        if (rc == SQLITE_ROW) return true;
        return false;
    }
    
    bool SQLiteStatement::NextRow() {
        int rc = sqlite3_step(stmt_);
    
        if (rc == SQLITE_ROW) {
            return true;
        }
        if (rc == SQLITE_DONE) {
            sqlite3_reset(stmt_);
            return false;
        }
        else if (rc == SQLITE_MISUSE) {
            //::MessageBox(0, "SQLiteStatement::NextRow SQLITE_MISUSE", 0, 0);
            CCLog("%s", "SQLiteStatement::NextRow SQLITE_MISUSE");
        }
        else if (rc == SQLITE_BUSY) {
            //::MessageBox(0, "SQLiteStatement::NextRow SQLITE_BUSY", 0, 0);
            CCLog("%s", "SQLiteStatement::NextRow SQLITE_BUSY");
        }
        else if (rc == SQLITE_ERROR) {
            //::MessageBox(0, "SQLiteStatement::NextRow SQLITE_ERROR", 0, 0);
            CCLog("%s", "SQLiteStatement::NextRow SQLITE_ERROR");
        }
        return false;
    }
    
    bool SQLiteWrapper::DirectStatement(std::string const& stmt) {
        char *errmsg;
        int   ret;
    
        ret = sqlite3_exec(db_, stmt.c_str(), 0, 0, &errmsg);
    
        if (ret != SQLITE_OK) {
            return false;
        }
        return true;
    
        //if(ret != SQLITE_OK) {
        //  std::cout << stmt << " [" << errmsg << "]" << std::endl;
        //}
    }
    
    std::string SQLiteWrapper::LastError() {
        return sqlite3_errmsg(db_);
    }
    
    bool SQLiteWrapper::Begin() {
        return DirectStatement("begin");
    }
    
    bool SQLiteWrapper::Commit() {
        return DirectStatement("commit");
    }
    
    bool SQLiteWrapper::Rollback() {
        return DirectStatement("rollback");
    }
    View Code

      使用方法如下:

    #include "SQLiteWrapper.h"
    #include <stdio.h>
    
    int main()
    {
        SQLiteWrapper sqlite;
        if (sqlite.Open("SQLiteWrapper.db")) {
            printf("%s", "SQLiteWrapper.db created or opened");
        }
        else {
            printf("%s", "couldn't open SQLiteWrapper.db");
        }
        if (sqlite.DirectStatement("create table if not exists foo(id integer primary key autoincrement,name text,age integer)")) {
            printf("%s", "table foo created");
        }
        else {
            printf("%s", "Couldn't create table foo");
        }
        if (sqlite.DirectStatement("insert into foo(name,age) values('2', 3);")) {
            printf("%s", "values (1,2) into foo inserted");
        }
        else {
            printf("%s", "Couldn't insert into foo");
        }
        sqlite.Close();
    }

    六、加密

      默认 sqlite3 是不需要用户名密码的,而且内置没有加密功能。但由于其是开源的,可以手动添加加密方案,也可以使用 wxsqlite3 这个开源的加密版 sqlite3 ,它使用 AES 加密方案。

      下载地址:http://wxcode.sourceforge.net/components/wxsqlite3/

      wxsqlite3 属于 wxWidgets ,需要先 yum install wxGTK-devel ,否则无法正确 ./configure ,会提示 wx-config 找不到。

  • 相关阅读:
    Python学习
    shell 脚本收藏
    无限级分类接口
    php 过滤多维数组中值为空的字段
    逆波兰表达式3(后缀表达式求值)
    [数据结构]之队列
    最大公约数和最小公倍数
    暗时间阅读笔记
    android判断文件是否是图片文件的方法
    android从assets读取文件的方法
  • 原文地址:https://www.cnblogs.com/tianyajuanke/p/3892945.html
Copyright © 2020-2023  润新知