本文分享一個使用 C 語言(KDevelop 3.3.4 IDE)封裝的 SQLite 操作庫,提供兩個核心函數:sqlite3_carrySql(執行非查詢 SQL)與 sqlite3_getResSet(執行查詢並回傳結果集),簡化應用層對 SQLite 的呼叫複雜度。
#ifndef _SQLITE3LIB_H_
#define _SQLITE3LIB_H_
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
typedef struct {
char **result; // 一維陣列儲存結果集(含欄位名)
int row; // 資料列數(不含欄位名列)
int col; // 欄位數
char *errmsg; // 錯誤訊息
} sqliteResSet;
/* 執行 INSERT/UPDATE/DELETE 等非查詢 SQL
成功回傳 0,失敗回傳非 0 並填充 errmsg
db: 資料庫檔案路徑(無需預先開啟)
sql: 要執行的 SQL 陳述式
errmsg: 呼叫端配置的緩衝區,用於接收錯誤訊息 */
int sqlite3_carrySql(const char *db, const char *sql, char *errmsg);
/* 執行 SELECT 查詢,結果存入 sqliteResSet
成功回傳 0,失敗回傳非 0
db: 資料庫檔案路徑
sql: 查詢 SQL
table: 呼叫端配置的 sqliteResSet 結構指標 */
int sqlite3_getResSet(const char *db, const char *sql, sqliteResSet *table);
#endif /* _SQLITE3LIB_H_ */
sqlite3* 控制代碼。result 為一維 char**,索引計算公式 index = col * row_idx + col_idx,第 0 列為欄位名稱。errmsg 緩衝區,函數將 SQLite 錯誤訊息複製過去。#include <stdio.h>
#include <stdlib.h>
#include "sqlite3Lib.h"
int main(int argc, char *argv[]) {
sqliteResSet table;
int result, i, j;
char *Errormsg = NULL; // 需初始化
// 1. 建表並插入測試資料
char *sql = "CREATE TABLE table1(id, name);"
"INSERT INTO table1 VALUES(1, 'Tom');"
"INSERT INTO table1 VALUES(2, 'Tom')";
result = sqlite3_carrySql("test.db", sql, Errormsg);
if (result) {
printf("資料庫操作失敗!\n");
return EXIT_FAILURE;
}
// 2. 查詢並列印結果
sql = "SELECT * FROM table1";
result = sqlite3_getResSet("test.db", sql, &table);
if (result) {
printf("查詢失敗!\n");
return EXIT_FAILURE;
}
printf("table1 全部資料:\n");
// 列印含欄位名的 (row+1) 列
for (i = 0; i < table.row + 1; i++) {
for (j = 0; j < table.col; j++) {
printf("%s\t", table.result[j + i * table.col]);
}
printf("\n");
}
// 實務上應釋放 table.result 記憶體(庫內需提供釋放函數)
return EXIT_SUCCESS;
}
sqlite3_free_table 釋放結果集,實務庫應提供 sqlite3_freeResSet(sqliteResSet*) 封裝釋放邏輯。sqlite3_exec_param 支援 sqlite3_bind_* 系列 API。sqlite3_begin/sqlite3_commit/sqlite3_rollback 封裝。這個輕量封裝庫展示如何將 SQLite C API 包裝成更符合應用層呼叫慣介面,適合作為專案內部資料存取層的基礎組件。