You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 7+中无法实例化SqliteConnection的问题排查

问题

在PowerShell 7+中尝试实例化Microsoft.Data.Sqlite.SqliteConnection时失败,抛出类型初始化异常。测试代码如下:

Add-Type -LiteralPath "path\to\Microsoft.Data.Sqlite.dll"
using namespace Microsoft.Data.Sqlite
$con = New-Object Microsoft.Data.Sqlite.SqliteConnection -ArgumentList "Data Source=hello.sqlite"

或另一种写法:

$con = [Microsoft.Data.Sqlite.SqliteConnection]::new("Data Source=hello.sqlite")

报错信息均为:

New-Object: Exception calling ".ctor" with "1" argument(s): "The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception."

原因及解决方法

核心原因

Microsoft.Data.Sqlite并非独立组件,它依赖SQLitePCLRaw提供的原生SQLite运行时库,仅加载Microsoft.Data.Sqlite.dll会导致底层依赖缺失,触发类型初始化失败。

具体解决步骤

  • 加载所有依赖组件
    从NuGet下载完整的Microsoft.Data.Sqlite包,解压后将以下关键DLL放到同一目录:

    • Microsoft.Data.Sqlite.dll
    • SQLitePCLRaw.core.dll
    • SQLitePCLRaw.batteries_v2.dll
    • 对应平台的原生sqlite3.dll(如runtimes/win-x64/native/sqlite3.dll)

    然后在PowerShell中加载所有托管DLL:

    # 假设所有DLL都在当前工作目录
    Add-Type -LiteralPath .\Microsoft.Data.Sqlite.dll, .\SQLitePCLRaw.core.dll, .\SQLitePCLRaw.batteries_v2.dll
    using namespace Microsoft.Data.Sqlite
    $con = [SqliteConnection]::new("Data Source=hello.sqlite")
    
  • 验证平台架构兼容性
    确认PowerShell的位数(64位/32位)与下载的原生sqlite3.dll位数一致。可通过以下命令查看当前PowerShell架构:

    [Environment]::Is64BitProcess
    

    返回True则需使用64位原生库,反之用32位。

  • 手动初始化SQLitePCLRaw(可选)
    若仍存在问题,可先手动初始化SQLitePCLRaw的电池组件,确保原生库被正确加载:

    Add-Type -LiteralPath .\SQLitePCLRaw.batteries_v2.dll
    [SQLitePCLRaw.Batteries_V2]::Initialize()
    
    Add-Type -LiteralPath .\Microsoft.Data.Sqlite.dll
    $con = [Microsoft.Data.Sqlite.SqliteConnection]::new("Data Source=hello.sqlite")
    

内容的提问来源于stack exchange,提问作者jgran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:35:24