背景
最近在学习《深入应用C++11: 代码优化与工程级应用》,其中第13章说到SQLite库,查询网上诸多教程,发现比较容易出现bug且配置较为麻烦,故记录此次简化版方案,以供参考。
软件环境
SQLite 3.42.0 版本(仅下载Source code即可)
VSCode+CMake+SQLite Viewer
测试代码
#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;
}
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)
# cmake needs this line
SET(CMAKE_BUILD_TYPE "Release")
add_library(sqlite3 ../include/sqlite3)
add_executable(main main.cpp)
target_link_libraries(main sqlite3)