首页 > 解决方案 > c# sqlite - 从数据库中检索 BLOB 文本

问题描述

我有一个带有单个表(当前)和 4 列的 sqlite 数据库:

Name //TEXT
Quote //TEXT
ImageURL //TEXT, an online image
Entry //Text BLOB, I want to parse and store this as a List<Entry>

我已经做了一些方法来创建文本文件、解析和存储数据以及删除文件。数据以这种格式存储:

$"{Index} {Time} {Date} {URL}" // "1 00:00.0 9/13/1985 www.stackoverflow.com"

...这样,拆分此字符串并将其存储在我的容器类中会更容易,Entry. 这些文件的大小平均为 250 字节,因此数据库内存很可能永远不会成为问题。

以下是连接到我表中的列数据的类:

public abstract class BaseClass
{
public abstract string Name {get; set;}
public abstract string ImageURL {get; set;}
public List<Entry> Records {get; private set;} //I already know .Add() is exposed, this problem has been fixed however.
...
}

public class DerivedClass : BaseClass
{
public override string Name {get; set;}
public override string ImageURL {get; set;}
public string Quote {get; set;}
...
}

我在过去几天看到的解决方案涉及不同的语言和/或 BLOB 类型,它们都没有同时使用 Dapper、Sqlite 和 C#。

到目前为止,我返回一个List<DerivedClass>包含单个元素的元素,该元素连接到上面显示的派生类中的属性。除了 BLOB 之外的所有内容。

public static ClassType GetSingleRow(string primaryKey) where ClassType : BaseClass
        { 
            using (IDbConnection connection = new SQLiteConnection(LoadConnectionString()))
            {                
                string sql = $"SELECT * FROM {typeof(ClassType).Name} WHERE Name = \"{primaryKey}\""; //probably vulnerable to sql injection but I'll worry about it later
                var output = connection.Query<ClassType>(sql, new DynamicParameters());
                //how would get a BLOB from this ienumearable?
                return output.ToList()[0]
            }
        }

重申一下,我如何能够使用 Dapper 从我的 sqlite 数据库中检索 BLOB 文本?我需要使用字节数组来检索它吗?如果是这样,我该怎么做?

标签: c#sqlitetextblobdapper

解决方案


好吧,就在我要发布这个问题之前,我想,“我为什么不创建另一个名为“Entry”的属性,以便 Dapper 可以为我完成剩下的工作。我string最初是这样做的,但后来我改变了得到它byte[]之后InvalidCastException

public class DerivedClass : BaseClass
{
public override string Name {get; set;}
public override string ImageURL {get; set;}
public string Quote {get; set;}
public byte[] Entry {get; set;}
...
}

然后在Main(),我可以做

Console.WriteLine(System.Text.Encoding.Default.GetString(DerivedClassObject.Entry));

使用我解析文本文件的方法,我可以轻松地将其存储在我的List<Entry>班级中。


推荐阅读