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

.NET Maui连接SQLite数据库时出现SQLite.Interop.dll找不到错误求助

解决.NET Maui中SQLite.Interop.dll找不到的问题

问题根源

你当前使用的System.Data.SQLite是针对传统Windows桌面应用(WinForms/WPF)设计的,依赖平台特定的SQLite.Interop.dll,而.NET Maui作为跨平台框架,无法在多平台环境下正确加载这个原生库,这是导致错误的核心原因。

解决方案步骤

1. 替换为Maui兼容的SQLite库

卸载所有已安装的System.Data.SQLite相关NuGet包,安装适合跨平台的SQLite库,推荐以下两个:

  • SQLite-net-pcl:轻量级ORM,易用性高,适合快速开发
  • Microsoft.Data.Sqlite:官方维护的ADO.NET风格库,功能更全面

2. 修正数据库路径

Maui是跨平台应用,不能使用Windows绝对路径(如D:\Program Files\SQLiteStudio\listview),需使用FileSystemAPI获取各平台的本地存储路径:

// 获取数据库文件的完整路径
string dbPath = Path.Combine(FileSystem.AppDataDirectory, "listview.db");

3. 修改连接代码示例

以SQLite-net-pcl为例,修改后的代码如下:

namespace MauiApp1;
using SQLite;

public partial class MainPage : ContentPage
{
    private SQLiteConnection _conn;

    public MainPage()
    {
        InitializeComponent();
        // 初始化数据库连接
        string dbPath = Path.Combine(FileSystem.AppDataDirectory, "listview.db");
        _conn = new SQLiteConnection(dbPath);
        // 如果表不存在则创建(可选)
        _conn.CreateTable<History>();
    }

    private void btnsubmit_Clicked(object sender, EventArgs e)
    {
        // 查询所有历史记录
        var historyList = _conn.Table<History>().ToList();
        // 提取需要的数据(假设History有Id字段,这里根据你的表结构调整)
        List<int> lstc = historyList.Select(h => h.Id).ToList();
        lstx.ItemsSource = lstc;
    }
}

// 定义与数据库表对应的实体类
public class History
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    // 添加你的其他字段,和数据库表结构对应
}

如果使用Microsoft.Data.Sqlite,代码示例如下:

namespace MauiApp1;
using Microsoft.Data.Sqlite;
using System.Collections.Generic;
using System.Linq;

public partial class MainPage : ContentPage
{
    private string _dbPath;

    public MainPage()
    {
        InitializeComponent();
        _dbPath = Path.Combine(FileSystem.AppDataDirectory, "listview.db");
    }

    private void btnsubmit_Clicked(object sender, EventArgs e)
    {
        using var conn = new SqliteConnection($"Data Source={_dbPath}");
        conn.Open();

        var query = "select Id from history";
        using var cmd = new SqliteCommand(query, conn);
        using var reader = cmd.ExecuteReader();

        List<int> lstc = new List<int>();
        while (reader.Read())
        {
            lstc.Add(reader.GetInt32(0));
        }

        lstx.ItemsSource = lstc;
    }
}

额外注意事项

  • 如果你需要读取已有的SQLite数据库文件,需将文件复制到Maui应用的本地存储路径中(可通过Maui的文件选择功能或打包时嵌入资源实现)
  • 确保安装的NuGet包版本与你的.NET Maui SDK版本兼容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:37:41