#include <iostream> #include "sqlite3.h" using namespace std; 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; #pragma endregion #pragma region 创建数据库表 const char *sqlCreateTable = "CREATE TABLE [t1](id integer PRIMARY KEY AUTOINCREMENT UNIQUE, name varchar);"; sqlite3_stmt *stmtCreateTable = NULL; /*检查语句合法性,-1代表系统会自动计算SQL语句的长度*/ result = sqlite3_prepare_v2(db, sqlCreateTable, -1, &stmtCreateTable, NULL); if (result == SQLITE_OK) { /*执行该SQL语句*/ sqlite3_step(stmtCreateTable); cout << "CREATE TABLE 语句执行成功" << endl; } else { cout << "CREATE TABLE 语句语法不正确:" << sqlite3_errmsg(db) << endl; } sqlite3_finalize(stmtCreateTable); #pragma endregion #pragma region 向数据库中插入数据 const char *sqlInsert = "INSERT INTO t1(name) VALUES('张三'); "; sqlite3_stmt *stmtInsert = NULL; /*检查语句合法性,-1代表系统会自动计算SQL语句的长度*/ result = sqlite3_prepare_v2(db, sqlInsert, -1, &stmtInsert, NULL); if (result == SQLITE_OK) { /*执行该SQL语句*/ sqlite3_step(stmtInsert); cout << "INSERT 语句执行成功" << endl; } else { cout << "INSERT 语句语法不正确:" << sqlite3_errmsg(db) << endl; } sqlite3_finalize(stmtInsert); #pragma endregion #pragma region 从数据库中查询数据 const char *sqlQuery = "SELECT * FROM t1;"; sqlite3_stmt *stmtQuery = NULL; /*检查语句合法性,-1代表系统会自动计算SQL语句的长度*/ result = sqlite3_prepare_v2(db, sqlQuery, -1, &stmtQuery, NULL); if (result == SQLITE_OK) { /*执行该SQL语句*/ while (sqlite3_step(stmtQuery) == SQLITE_ROW) { // 取出第0列字段的值 int id = sqlite3_column_int(stmtQuery, 0); // 取出第1列字段的值 const unsigned char *name = sqlite3_column_text(stmtQuery, 1); //输出相关查询的数据 cout << "id:" << id << ", name: " << name << endl; } } else { cout << "SELECT 语句语法不正确:" << sqlite3_errmsg(db) << endl; } sqlite3_finalize(stmtQuery); #pragma endregion sqlite3_close(db); } int main(int argc, char *argv[]) { dbTest(); char sz[] = "End !"; cout << sz << endl; return 0; }