在 Windows CE / Windows Mobile 環境下使用 SQLite,需針對 ARM/MIPS/x86 交叉編譯 SQLite 原始碼,並正確設定 VS2008 專案的包含目錄、庫目錄與連結器選項。本文提供從原始碼編譯到專案整合的完整流程。
sqlite3.c、sqlite3.h、sqlite3ext.h(官網下載 sqlite-amalgamation-xxxxxxx.zip)SQLITE_OS_WIN=1; SQLITE_OMIT_LOAD_EXTENSION=1; HAVE_USLEEP=1; _CRT_SECURE_NO_WARNINGS
#include "sqlite3.h"
#pragma comment(lib, "SQLiteCE.lib")
#include "sqlite3.h"
#include // CString
void TestSQLite()
{
sqlite3 *db = nullptr;
int rc = sqlite3_open(_T("\\My Documents\\test.db"), &db); // CE 路徑用反斜線
if (rc != SQLITE_OK) {
CString err; err.Format(_T("Open failed: %s"), sqlite3_errmsg(db));
AfxMessageBox(err); return;
}
// 建表
const char *sql = "CREATE TABLE IF NOT EXISTS users("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"name TEXT NOT NULL,"
"age INTEGER);";
char *errMsg = nullptr;
rc = sqlite3_exec(db, sql, nullptr, nullptr, &errMsg);
if (rc != SQLITE_OK) {
AfxMessageBox(CString(errMsg)); sqlite3_free(errMsg);
}
// 參數化插入
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "INSERT INTO users(name,age) VALUES(?,?);", -1, &stmt, nullptr);
sqlite3_bind_text(stmt, 1, "Alice", -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 2, 25);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
// 查詢
sqlite3_prepare_v2(db, "SELECT id,name,age FROM users;", -1, &stmt, nullptr);
while (sqlite3_step(stmt) == SQLITE_ROW) {
int id = sqlite3_column_int(stmt, 0);
const char *name = (const char*)sqlite3_column_text(stmt, 1);
int age = sqlite3_column_int(stmt, 2);
CString s; s.Format(_T("ID:%d Name:%s Age:%d"), id, name, age);
AfxMessageBox(s);
}
sqlite3_finalize(stmt);
sqlite3_close(db);
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 連結錯誤 LNK2019: sqlite3_open | 未連結 SQLite 靜態庫 | 檢查「附加相依性」含 `SQLiteCE.lib` |
| 執行時「找不到 sqlite3.dll」 | WinCE 無預設 SQLite,必須靜態連結 | 專案屬性 → C/C++ → 程式碼產生 → 執行階段程式庫:`/MT` (靜態) 或確保裝置有 DLL |
| 路徑錯誤 unable to open database file | WinCE 路徑格式不同 | 用絕對路徑 ` |
| 中文亂碼 | SQLite 預設 UTF-8,CE 系統預設 MBCS | 字串存入前 `WideCharToMultiByte(CP_UTF8,...)`,讀出後 `MultiByteToWideChar(CP_UTF8,...)` |
| 多執行緒存取死結 | 預設序列化模式 | `sqlite3_config(SQLITE_CONFIG_SERIALIZED)` 或開啟 WAL 模式 `PRAGMA journal_mode=WAL;` |
sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr);
sqlite3_exec(db, "PRAGMA synchronous=NORMAL;", nullptr, nullptr, nullptr);
https://www.sqlite.org/compile.htmlhttps://learn.microsoft.com/en-us/previous-versions/windows/embedded/https://www.docin.com/p-632122826.html遵循「交叉編譯靜態庫 → 專案正確引用 → 路徑/編碼/並發正確處理」三步驟,即可在 VS2008 MFC 智慧裝置專案中穩定使用 SQLite 3。