VSCode配置之C++ & SQLite3极简配置方案

  1. 背景
    最近在学习《深入应用C++11: 代码优化与工程级应用》,其中第13章说到SQLite库,查询网上诸多教程,发现比较容易出现bug且配置较为麻烦,故记录此次简化版方案,以供参考。

  2. 软件环境
    SQLite 3.42.0 版本(仅下载Source code即可)
    VSCode+CMake+SQLite Viewer
    VSCode配置之C++ & SQLite3极简配置方案_第1张图片

  3. VSCode + SQLite文件目录
    VSCode配置之C++ & SQLite3极简配置方案_第2张图片
    (注:仅需左侧红色框内容,其余均为编译生成结果)

  4. 测试代码

#include
#include
#include"sqlite3.h"

using namespace std;

bool test_sqlite() {
  sqlite3* db_handle = nullptr;
    int result = sqlite3_open("test.db", &db_handle);
    if(result != SQLITE_OK) {
        sqlite3_close(db_handle);
        return false;
    }

    // create table
    const char* sql_create = "CREATE TABLE if not exists personTable(ID INTEGER NOT NULL, Name Text, Address Text);";
    result = sqlite3_exec(db_handle, sql_create, nullptr, nullptr, nullptr);

    // insert data
    // create stmt
    sqlite3_stmt* stmt = nullptr;
    const char* sql_insert = "INSERT INTO personTable(ID, Name, Address) VALUES(?, ?, ?);";
    sqlite3_prepare_v2(db_handle, sql_insert, strlen(sql_insert), &stmt, nullptr);
    
    // update data
    int id = 1;
    const char* name = "Sqlite3";
    const char* address = "Database";
    sqlite3_bind_int(stmt, 1, id);
    sqlite3_bind_text(stmt, 2, name, strlen(name), SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 3, address, strlen(address), SQLITE_TRANSIENT);
    sqlite3_step(stmt);
    result = sqlite3_exec(db_handle, sql_insert, nullptr, nullptr, nullptr);

    // free stmt
    sqlite3_finalize(stmt);

    // close sqlite
    sqlite3_close(db_handle);
    return result = SQLITE_OK;
}

int main() {
    cout << test_sqlite() << endl;
    return 0;
}
  1. 外层CMakeLists.txt配置
cmake_minimum_required (VERSION 3.0)

PROJECT(sqlite3_demo)

set(CMAKE_BUILD_TYPE Release)

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin) 
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
include_directories(${PROJECT_SOURCE_DIR}/include)
link_directories(${PROJECT_SOURCE_DIR}/lib)
add_subdirectory(${PROJECT_SOURCE_DIR}/src)

  1. 内层CMakeLists.txt配置
# cmake needs this line
SET(CMAKE_BUILD_TYPE "Release")

add_library(sqlite3 ../include/sqlite3)
add_executable(main main.cpp)
target_link_libraries(main sqlite3)
  1. 小结
    1)理解了CMake的编译原理就不在需要诸如sqlite3.def,sqlite3.exe文件,通过手动编译的方式,自动生成sqlite3.lib,更加实用便捷,且不需要调用vs studio的lib.exe等命令(需要管理员权限);
    2)SQLite提供了丰富的API,因此手动编译源码,方便函数的查询和源码的理解;
    3)SQLite的数据处理pipeline较为繁琐,接下来将尝试书中方法,进行二次封装简化。

你可能感兴趣的:(C++,VSCode,vscode,c++,sqlite)