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

如何使用SQLiteConnection连接加密shopdata.db并获取数据?

连接加密SQLite数据库并获取数据

你提供的初始化代码存在两处问题:文件名拼写错误(shopdate.db应为shopdata.db)、连接字符串未闭合(末尾缺少双引号),先修正这部分,再实现数据查询逻辑:

1. 修正连接初始化代码

public class SQLiteConnect
{
    private SQLiteConnection con;
    private SQLiteCommand cmd;

    public SQLiteConnect()
    {
        // 修正文件名拼写,补全字符串闭合引号
        this.con = new SQLiteConnection("Data Source=shopdata.db;Password=123");
        this.cmd = new SQLiteCommand();
        this.cmd.Connection = this.con;
    }
}

2. 实现数据查询方法

添加方法执行查询并获取数据,示例如下:

public List<Dictionary<string, object>> GetShopData(string sqlQuery)
{
    var resultList = new List<Dictionary<string, object>>();
    try
    {
        con.Open(); // 打开数据库连接
        cmd.CommandText = sqlQuery;
        using (SQLiteDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                var row = new Dictionary<string, object>();
                // 遍历当前行所有列,将列名和值存入字典
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    row[reader.GetName(i)] = reader.GetValue(i);
                }
                resultList.Add(row);
            }
        }
    }
    catch (Exception ex)
    {
        // 根据需求处理异常,比如打印日志
        Console.WriteLine($"查询出错:{ex.Message}");
    }
    finally
    {
        if (con.State == System.Data.ConnectionState.Open)
        {
            con.Close(); // 确保连接关闭
        }
    }
    return resultList;
}

注意事项

  • 确保使用的SQLite组件支持加密功能,比如官方的System.Data.SQLite库,部分轻量库可能不支持加密数据库连接。
  • 连接字符串中的Password参数对应加密时设置的密钥,若使用SQLCipher等其他加密方案,可能需要改用Key参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:10:28