針對嵌入式 Linux 環境(KDevelop 3.3.4),封裝 SQLite 3 C API 為兩個核心函數:sqlite3_carrySql(執行增刪改)與 sqlite3_getResSet(查詢並回傳結果集),簡化應用層開發。
sqlite3Lib.h#ifndef _SQLITE3LIB_H_
#define _SQLITE3LIB_H_
#include
#include
#include
typedef struct {
char **result; // 一維陣列:[0..col-1] 為欄位名,之後每 row * col 為一列資料
int row; // 資料列數(不含欄位名列)
int col; // 欄位數
char *errmsg; // 錯誤訊息
} sqliteResSet;
/* 執行非查詢 SQL(INSERT/UPDATE/DELETE/CREATE...)
成功回傳 0,errmsg 需呼叫端釋放 */
int sqlite3_carrySql(const char *db, const char *sql, char *errmsg);
/* 執行查詢 SQL,結果存入 sqliteResSet
成功回傳 0,結果集於 table->result,呼叫端需自行釋放 */
int sqlite3_getResSet(const char *db, const char *sql, sqliteResSet *table);
#endif
sqlite3_carrySql:sqlite3_open → sqlite3_exec → sqlite3_close,錯誤訊息複製至 errmsg。sqlite3_getResSet:使用 sqlite3_get_table 一次取得完整結果集(含欄位名),填入 sqliteResSet 結構。table->result(sqlite3_free_table)與 errmsg。#include
#include
#include "sqlite3Lib.h"
int main() {
sqliteResSet table;
int rc;
char *errmsg = NULL;
// 建表並插入資料
char *sql = "CREATE TABLE table1(id, name);"
"INSERT INTO table1 VALUES(1, 'Tom');"
"INSERT INTO table1 VALUES(2, 'Tom')";
rc = sqlite3_carrySql("test.db", sql, errmsg);
if (rc) { printf("操作失敗!\n"); return 1; }
// 查詢
sql = "SELECT * FROM table1";
rc = sqlite3_getResSet("test.db", sql, &table);
if (rc) { printf("查詢失敗!\n"); return 1; }
printf("table1 完整資料:\n");
for (int i = 0; i < table.row + 1; ++i) { // +1 含欄位名列
for (int j = 0; j < table.col; ++j) {
printf("%s\t", table.result[j + i * table.col]);
}
printf("\n");
}
sqlite3_free_table(table.result);
return 0;
}
table1 完整資料:
id name
1 Tom
2 Tom
sqlite3_prepare_v2/sqlite3_bind_*)、交易控制、預編譯語句快取。SQLITE_THREADSAFE=1 並使用序列化模式。此輕量封裝保留 SQLite 原生效能,同時提供類似 JDBC/ADO.NET 的結果集存取介面,適合 C/C++ 專案快速整合。