System.Data.SQLite 的非託管核心 `SQLite.Interop.dll` 預設動態連結 VC++ Runtime (MSVCRT),導致未安裝對應 Visual C++ Redistributable 的機器無法執行。解決方案:重新編譯 `SQLite.Interop.dll` 為**靜態連結** (`/MT` 或 `/MTd`),使其內建 Runtime 程式碼,單一 DLL 即可獨立執行。
System.DllNotFoundException: 無法載入 DLL 'SQLite.Interop.dll':應用程式組態不正確 (0x800736B1) -- 通常因目標機器缺少 VC++ 2005/2010/2013/2015/2017/2019 Redistributable
SQLite 官網已提供靜態連結版本下載,無需自行編譯:
static、bundle、Win32/x64sqlite-netFx47-static-binary-bundle-x64-2017-1.0.117.0.zip若官方版本不符需求 (如特定 .NET Framework 版本、自訂編譯選項),可自行編譯:
git clone https://github.com/sqlite/sqlite.git # 或下載 System.Data.SQLite 官方原始碼套件 (含 VS 專案檔)
| 設定頁面 | 屬性 | 修改為 |
|---|---|---|
| C/C++ → 代碼產生 | 執行階段程式庫 | 多執行緒 (/MT) (Release) 多執行緒偵錯 (/MTd) (Debug) |
| 資訊清單工具 → 輸入和輸出 | 內嵌資訊清單 | 否 |
| 連結器 → 資訊清單檔 | 產生資訊清單 | 否 |
# 批次建置腳本 msbuild SQLite.Interop.2019.vcxproj /p:Configuration=Release /p:Platform=Win32 msbuild SQLite.Interop.2019.vcxproj /p:Configuration=Release /p:Platform=x64
# 使用 Dependency Walker (depends.exe) 或 dumpbin dumpbin /imports SQLite.Interop.dll # 若無 MSVCRT.dll、VCRUNTIME140.dll 等匯入,即為靜態連結成功
| 檔案 | 放置位置 | 說明 |
|---|---|---|
| System.Data.SQLite.dll | Bin/ 或 GAC | 託管包裝層,Any CPU |
| SQLite.Interop.dll (x86) | Bin/x86/ | 32 位元進程載入 |
| SQLite.Interop.dll (x64) | Bin/x64/ | 64 位元進程載入 |
| 資料庫檔 .db/.sqlite | App_Data/ 或指定路徑 | 連線字串 Data Source=... |
// 相對路徑 (App_Data) string connStr = "Data Source=|DataDirectory|\\MyDb.sqlite;Version=3;"; // 絕對路徑 string connStr = "Data Source=C:\\Data\\MyDb.sqlite;Version=3;Pooling=true;Cache Size=4096;"; // 加密資料庫 (需 SEE 擴充版) string connStr = "Data Source=MyDb.sqlite;Version=3;Password=MySecret;";
| 問題 | 原因與解決 |
|---|---|
| BadImageFormatException | 進程位元數與 Interop.dll 不符。確保專案 Platform target (x86/x64/Any CPU) 與部署的 Interop.dll 一致。Any CPU + Prefer 32-bit 勾選 → 需 x86 Interop。 |
| DllNotFoundException (x64) | 64 位元機器未部署 x64 版 Interop.dll。檢查 Bin/x64/ 存在。 |
| 資料庫鎖定/寫入失敗 | SQLite 檔案層級鎖定。連線字串加 `Pooling=true`、避免長連線、WAL 模式 `PRAGMA journal_mode=WAL;`。 |
| Entity Framework Core 搭配 | 使用 `Microsoft.Data.Sqlite` (純託管) 或 `Microsoft.EntityFrameworkCore.Sqlite` (內建原生),無需手動管理 Interop.dll。 |