【问题标题】:How to retrieve byte array from SQLite database in UWP using C#如何使用 C# 从 UWP 中的 SQLite 数据库中检索字节数组
【发布时间】:2017-08-03 22:01:48
【问题描述】:

我搜索了太久,但找不到任何答案。

我正在开发一个 UWP 应用程序,它将 BitmapImage 数据(转换为字节数组)存储到 SQLite3 数据库中的 blob 字段中。但是,一旦将数据保存在数据库中,我就找不到检索数据的方法。

我见过的所有解决方案都使用 Microsoft.Data.SQLite.SQLiteDataReader 中的 GetBytes 方法,但 Microsoft 的文档表明该方法“不受支持”。 https://docs.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitedatareader.getbytes?view=msdata-sqlite-1.1.0

谁能展示一些示例代码如何从 SQLite 3 数据库中检索 blob 并将其转换为 BitmapImage 以进行显示?

提前感谢您的帮助。

【问题讨论】:

  • 谢谢,但它似乎没有显示任何关于如何从数据库中读回字节数组的信息。
  • This says 使用reader.GetFieldValue<byte[]>()
  • @ArthusLeSavage 实体框架是一种用于处理转换为数据库中表的对象的工具。创建一个具有字节数组的类,并创建一个具有正确数据类型的表,当您运行查询时,您会得到一个字节数组。
  • 如果您使用byte[] 来存储字节,那么您不需要使用“GetBytes”。例如-这是您的模型:public byte[] ImageAsBytes {get; set;} 然后您可以像 var bytes = db.TableName.ImageAsBytes.FirstOrDefault( r => r.primaryKey == value ); 一样简单地访问它

标签: c# xaml uwp


【解决方案1】:

这是所需工作的真正最小版本,但它为您提供了将图片数据存储为btye[] 的步骤,也可以将数据作为字节数组检索。

我不会深入探讨实体框架,因为这不是问题的一部分,我相信这个链接做得很好。 Microsoft Documentation.

免责声明我从未使用过UWP的实体框架,也从未使用过SQL Lite数据库,可能存在数据量和所有可用类型都可以存储的东西在数据库中。

UWP中byte[]转BitMap,看here

public class ProfilePictures
{
    public int ProfilePicturePK {get;set;}
    public byte[] PictureData {get;set;}
}

... all the other entity setup, see link for entity setup

public byte[] GetPictureData(int id)
{
    return GetPictureDataAsync(id).Wait();
}

//If you want to make things a little more UI and thread friendly
public async Task<byte[]> GetPictureDataAsync(int id)
{
     await Task.Factory.StartNew(()=>{
        using(var db = Context)
        {
            return (from pictures in db.ProfilePictures where pictures.ProfilePicturePK == id select pictures).SingleOrDefault();
        }
     });
}

【讨论】:

  • 感谢您的帮助。我接受了 Crowcoder 的建议来检索 BLOB 字段。
猜你喜欢
  • 2021-10-14
  • 2011-05-10
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
相关资源
最近更新 更多