sqlite3在C++中的基础使用

oneNeko 于 2020-08-07 发布

sqlite 是一个轻量级的关系数据库,使用方便,占用小,不必复杂的安装

下载

访问 sqlite 官网https://www.sqlite.org/download.html,下载源代码(sqlite-amalgamation-3320300.zip)和对应的dll包、工具包,我的是windows,所以下载sqlite-dll-win32-x86-3320300.zip
解压后,将dll包和工具包解压到一起,然后在电脑的环境变量里添加路径

测试

打开cmd,输入sqlite3 即可进入sqlite,此时打开的数据库是在内存里的临时数据库,如下:

E:\tools\sqlite>sqlite3
SQLite version 3.32.3 2020-06-18 14:00:33
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite>

可以使用.help命令查看操作命令

C++ 使用

为了方便使用,我们在vs工程 属性-链接器-输入-附加依赖项,添加sqlite3.lib,如果下载的包里面没有sqlite3.lib,就只能自己编译:

sqlite3,lib放进工程里,sqlite3.dll放入exe文件夹
然后在代码中使用,如:

#include "sqlite3.h"

static int callback(void *data, int argc, char **argv, char **azColName) {
	int i;
	fprintf(stderr, "%s: ", (const char*)data);
	for (i = 0; i<argc; i++) {
		std::string azCol = azColName[i];
		std::string arg=argv[i];
		//自定义操作
	}
	printf("\n");
	return 0;
}

int main(){
    sqlite3* conn;

    //打开数据库
    if (sqlite3_open("test.db", conn) != SQLITE_OK) { 
		printf("open error");
        return 0;
	}

    //执行sql语句
    char* sql="select * from my_test";
    char* msg="";
	const char* data="callback";
	int lRet = sqlite3_exec(conn, sql, callback, (void*)data, &msg);

    //关闭数据库
    if (sqlite3_close(conn) != SQLITE_OK) { 
		printf("close error")
	}
    return 0;
}