#include <iostream> #include <string.h> #include "sqlite3.h" using namespace std; static int callback(void *notUsed, int argc, char **argv, char **azColName) { for (int i = 0; i < argc; i++) cout << azColName[i] << ":" << (argv[i] ? argv[i] : "NULL") << "\t"; cout << endl; return 0; } void dbTest() { #pragma region 打开或创建数据库 /*打开或创建的数据库实例句柄*/ sqlite3 *db = NULL; /*数据库文件的路径及文件名*/ const char* path = "./sqlcipher.db"; /*根据文件路径打开数据库连接。如果数据库不存在,则创建。数据库文件的路径必须以C字符串传入*/ int result = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_SHAREDCACHE, NULL); if (result == SQLITE_OK) cout << "打开或创建数据库成功" << endl; else cout << "打开或创建数据库失败" << endl; sqlite3_close(db); #pragma endregion #pragma region 指定数据库密码 const char* pwd = "abcdefg"; result = sqlite3_open(path, &db); if (result == SQLITE_OK) cout << "打开数据库成功" << endl; else cout << "打开数据库失败" << endl; result = sqlite3_key(db, pwd, strnlen(pwd, 1000)); cout << "指定数据库密码:" << result << endl; #pragma endregion #pragma region 执行SQL语句 char* errmsg; result = sqlite3_exec(db, "CREATE TABLE [t1](id integer PRIMARY KEY AUTOINCREMENT UNIQUE, name varchar);", NULL, NULL, &errmsg); if (result == SQLITE_OK) { cout << "SQL 语句执行成功" << endl; } else { cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl; } result = sqlite3_exec(db, "INSERT INTO t1(name) VALUES('张三');", NULL, NULL, &errmsg); if (result == SQLITE_OK) { cout << "SQL 语句执行成功" << endl; } else { cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl; } result = sqlite3_exec(db, "SELECT * FROM t1;", callback, NULL, &errmsg); if (result == SQLITE_OK) { cout << "SQL 语句执行成功" << endl; } else { cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl; } #pragma endregion sqlite3_close(db); } int main(int argc, char *argv[]) { dbTest(); char sz[] = "End !"; cout << sz << endl; return 0; }