-
背景
最近在学习《深入应用C++11: 代码优化与工程级应用》,其中第13章说到SQLite库,查询网上诸多教程,发现比较容易出现bug且配置较为麻烦,故记录此次简化版方案,以供参考。 -
软件环境
SQLite 3.42.0 版本(仅下载Source code即可)
VSCode+CMake+SQLite Viewer -
VSCode + SQLite文件目录
(注:仅需左侧红色框内容,其余均为编译生成结果)文章来源:https://www.toymoban.com/news/detail-621986.html -
测试代码文章来源地址https://www.toymoban.com/news/detail-621986.html
#include<iostream>
#include<string>
#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;
}
- 外层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)
- 内层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)理解了CMake的编译原理就不在需要诸如sqlite3.def,sqlite3.exe文件,通过手动编译的方式,自动生成sqlite3.lib,更加实用便捷,且不需要调用vs studio的lib.exe等命令(需要管理员权限);
2)SQLite提供了丰富的API,因此手动编译源码,方便函数的查询和源码的理解;
3)SQLite的数据处理pipeline较为繁琐,接下来将尝试书中方法,进行二次封装简化。
到了这里,关于VSCode配置之C++ & SQLite3极简配置方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!