首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

cocos2d-x 資料持久化實戰 (二):SQLite 原生 C API 整合完整教學

     編輯:關於C語言

環境整合:零配置嵌入 SQLite

  1. 下載 SQLite Amalgamation (單檔版:sqlite3.c, sqlite3.h, sqlite3ext.h, shell.c)
  2. 解壓至引擎目錄 (如 cocos2d-x/external/sqlite/)
  3. VS 專案 → 屬性 → C/C++ → General → Additional Include Directories 加入上述路徑
  4. 專案 → Add Existing Item → 選擇 sqlite3.c (僅需此檔,shell.c 為命令列工具用)

VS 專案加入 sqlite3.c 設定包含目錄

核心 API 快速上手


#include "sqlite3.h"

sqlite3* pDB = nullptr;
char* errMsg = nullptr;
int result;

// 1. 開啟/建立資料庫
result = sqlite3_open("save.db", &pDB);
if (result != SQLITE_OK) { CCLog("Open failed: %s", errMsg); return; }

// 2. 建立資料表 (ID 主鍵自增)
result = sqlite3_exec(pDB,
    "CREATE TABLE IF NOT EXISTS MyTable_1 (ID INTEGER PRIMARY KEY AUTOINCREMENT, name NVARCHAR(32))",
    nullptr, nullptr, &errMsg);

// 3. 插入資料
std::string sql = "INSERT INTO MyTable_1 (name) VALUES ('克塞')";
sqlite3_exec(pDB, sql.c_str(), nullptr, nullptr, &errMsg);
// ... 重複插入 '葫蘆娃', '擎天柱'

// 4. 關閉
sqlite3_close(pDB);

視覺化管理工具:SQLite Database Browser

跨平台 Qt 開發,極簡易用。開啟專案 Resources/save.db 即可瀏覽表結構、資料列、執行任意 SQL。下載:SourceForge。

SQLite Database Browser 介面

常用操作範例大全 (含回調函數模式)

1. 更新 / 刪除


// 更新 ID=3 名稱為 '威震天'
sqlite3_exec(pDB, "UPDATE MyTable_1 SET name='威震天' WHERE ID=3", nullptr, nullptr, &errMsg);
// 刪除 ID=2
sqlite3_exec(pDB, "DELETE FROM MyTable_1 WHERE ID=2", nullptr, nullptr, &errMsg);

2. 判斷表是否存在


bool isExisted = false;
auto callback = [](void* para, int nCol, char** colVal, char** colName) -> int {
    *static_cast(para) = (colVal[0][0] != '0');
    return 0;
};
sqlite3_exec(pDB,
    "SELECT COUNT(type) FROM sqlite_master WHERE type='table' AND name='MyTable_1'",
    callback, &isExisted, &errMsg);

3. 判斷記錄是否存在


bool hasRecord = false;
sqlite3_exec(pDB,
    "SELECT COUNT(*) FROM MyTable_1 WHERE ID=2",
    callback, &hasRecord, &errMsg); // 同樣回調

4. 取得記錄總數


int count = 0;
auto countCb = [](void* para, int nCol, char** colVal, char** colName) -> int {
    *static_cast(para) = nCol; // 注意:這裡 nCol 是欄位數,若 SELECT * 則等於欄位數;實際應用建議用 COUNT(*)
    return 0;
};
sqlite3_exec(pDB, "SELECT * FROM MyTable_1", countCb, &count, &errMsg);

5. 讀取單筆記錄並列印


auto printCb = [](void* para, int nCol, char** colVal, char** colName) -> int {
    CCLog("ID=%s, name=%s", colVal[0], colVal[1]);
    return 0;
};
sqlite3_exec(pDB, "SELECT * FROM MyTable_1 WHERE ID=3", printCb, nullptr, &errMsg);

進階主題預告

  • Prepared Statement (sqlite3_prepare_v2) 防 SQL Injection、提升重複執行效能
  • Transaction (BEGIN/COMMIT) 批次寫入加速
  • WAL 模式 (PRAGMA journal_mode=WAL) 提升並發讀寫效能
  • 資料加密 (SQLCipher) 防存檔竄改
  • 跨平台路徑處理 (CCFileUtils::getWritablePath())

SQLite 以「零配置、單一檔案、ACID 完整」成為手遊儲存首選。掌握原生 C API,才能在效能與安全上做極致優化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved