共用方式為


自訂 SQLite 版本

Microsoft.Data.Sqlite 是建置在 SQLitePCLRaw 之上。 您可以使用套件組合或設定 SQLitePCLRaw 提供者,來使用原生 SQLite 程式庫的自訂版本。

套件組合

SQLitePCLRaw 提供方便的套件組合套件,可讓您輕鬆地在不同的平台間導入正確的相依性。 主要 Microsoft.Data.Sqlite 套件預設會帶入 SQLitePCLRaw.bundle_e_sqlite3。 若要使用不同的套件組合,請改為連同您想要使用的套件組合套件來安裝 Microsoft.Data.Sqlite.Core 套件。 套件組合會自動由 Microsoft.Data.Sqlite 初始化。

套件組合 描述
SQLitePCLRaw.bundle_e_sqlite3 在所有平台上提供一致的 SQLite 版本。 包含 FTS4、FTS5、JSON1 和 R* 樹狀結構延伸模組。 這是預設值。
SQLitePCLRaw.bundle_e_sqlcipher 提供非官方的 SQLCipher 開放原始碼組建。
SQLitePCLRaw.bundle_green bundle_e_sqlite3 相同,但使用系統 SQLite 程式庫的 iOS 除外。
SQLitePCLRaw.bundle_sqlite3 使用系統 SQLite 程式庫。
SQLitePCLRaw.bundle_winsqlite3 使用 Windows 10 上的系統 SQLite 程式庫 winsqlite3.dll
SQLitePCLRaw.bundle_zetetic 使用來自 Zetetic (不包含) 的官方 SQLCipher 組建。

例如,若要使用非官方的 SQLCipher 開放原始碼組建,請使用下列命令。

dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.bundle_e_sqlcipher

SQLitePCLRaw 可用的提供者

當不依賴套件組合時,您可以使用 SQLite 的可用提供者搭配核心組件。

提供者 描述
SQLitePCLRaw.provider.dynamic dynamic 提供者會載入原生程式庫,而不是使用 System.Runtime.InteropServices.DllImportAttribute 屬性。 如需使用此提供者的詳細資訊,請參閱使用動態提供者
SQLitePCLRaw.provider.e_sqlite3 e_sqlite3 是預設提供者。
SQLitePCLRaw.provider.e_sqlcipher e_sqlcipher 提供者是非官方且不受支援的 SQLCipher
SQLitePCLRaw.provider.sqlite3 sqlite3 提供者是 iOS、macOS 和 Linux 版系統提供的 SQLite
SQLitePCLRaw.provider.sqlcipher sqlcipher 提供者適用於 Zetetic 中的官方 SQLCipher 組建。
SQLitePCLRaw.provider.winsqlite3 winsqlite3 提供者適用於 Windows 10 環境。

若要使用 sqlite3 提供者,請使用下列命令:

dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.core
dotnet add package SQLitePCLRaw.provider.sqlite3

安裝套件之後,您會將提供者設定為 sqlite3 執行個體。

using Microsoft.Data.Sqlite;
using System;

namespace SqliteProviderSample
{
    class Program
    {
        static void Main()
        {
            SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());

            using var connection = new SqliteConnection();
            Console.WriteLine($"System SQLite version: {connection.ServerVersion}");
        }
    }
}

使用動態提供者

您可以利用 SQLitePCLRaw.provider.dynamic_cdecl 套件來使用自己的 SQLite 組建。 在此情況下,您必須負責使用您的應用程式部署原生程式庫。 請注意,使用應用程式部署原生程式庫的詳細資料會因您使用的 .NET 平台和執行階段而有很大不同。

首先,您必須實作 IGetFunctionPointer。 .NET Core 上的實作如下所示:

class NativeLibraryAdapter : IGetFunctionPointer
{
    readonly IntPtr _library;

    public NativeLibraryAdapter(string name)
        => _library = NativeLibrary.Load(name);

    public IntPtr GetFunctionPointer(string name)
        => NativeLibrary.TryGetExport(_library, name, out var address)
            ? address
            : IntPtr.Zero;
}

接下來,設定 SQLitePCLRaw 提供者。 在您的應用程式中使用 Microsoft.Data.Sqlite 之前,請確定已完成此動作。 此外,請避免使用 SQLitePCLRaw 套件組合套件,這可能會覆寫提供者。

SQLite3Provider_dynamic_cdecl
    .Setup("sqlite3", new NativeLibraryAdapter("sqlite3"));
SQLitePCL.raw.SetProvider(new SQLite3Provider_dynamic_cdecl());