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.dllSQLitePCLRaw.core.dllSQLitePCLRaw.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
相关产品推荐
相关产品推荐

