【问题标题】:C# SQLite retrieve complete blob and insert complete blobC# SQLite 检索完整的 blob 并插入完整的 blob
【发布时间】:2021-03-09 01:03:21
【问题描述】:

大家好!目前我正在开发一个 c# 项目,该项目需要我从 .db3 sqlite 文件中检索图像并将其插入到另一个 .db3 文件中。我可以成功检索 blob 数据并将其作为图像保存在本地驱动器中。我的 blob 中有 3 种类型的值,它们是:十六进制、文本和图像。但是,当我尝试检索完整的十六进制值或图像时,我只能检索其中的文本值,因为文本是行中显示的值。我已经尝试在几个平台和谷歌上搜索,但这些解决方案仍然给我同样的结果。在这种情况下,我无法查看新数据库文件中的图像。我的代码是这样的:

rdrall.Read();
string rawimage = ($"{rdrall[5]}") ;
byte[] newByte = ToByteArray(rawimage);

string inserttbl1 = "INSERT INTO newtest3 (image) VALUES (" + "'" + newbyte + "'" + ")";

SQLiteCommand insert = new SQLiteCommand(inserttbl1, createnew);
insert.ExecuteNonQuery();

结果应该是这样的“??????”: expected output

但结果是这样的“system.byte[]”: actual output

并且实际输出不能作为图像查看。反正有没有让我检索整个值,或者只是将图像转换为格式?提前致谢!

【问题讨论】:

    标签: c# sqlite blob


    【解决方案1】:

    您正在数据库中插入一个System.byte[] 文本值,因为C# 中的字符串连接将调用对象的.ToString() 方法,byte[] 将使用通用方式来表示字符串中的对象(类型名称)而不是表示数组内容本身。

    如果你想在 blob 列中插入一个 byte[],我建议你使用 bind parameter:

    SqliteCommand command = new SqliteCommand("insert into newtest3 (id, name, image) values (@id, @name, @image)", connection);
    
    command.Parameters.Add("@id", SqliteType.Integer).Value = 10;
    command.Parameters.Add("@name", SqliteType.Text).Value = "john";
    command.Parameters.Add(new SqliteParameter()
    {
        ParameterName = "@image",
        Value = data,
        DbType = System.Data.DbType.Binary
    });
    command.ExecuteNonQuery();
    

    要将 blob 内容读取为 byte[],只需将列转换为 byte[]:

    SqliteCommand query = new SqliteCommand("select image from newtest3", connection);
    SqliteDataReader reader = query.ExecuteReader();
    while (reader.Read())
    {
        byte[] image = (byte[])reader["image"];
    }
    

    【讨论】:

    • 谢谢!我对参数有一些疑问,如果表中有多个字段,我可以知道如何添加更多参数吗?我尝试像这样添加,但错误仍然相同 commandimg.Parameters.Add(new SQLiteParameter() { ParameterName = "lotGUID", // or @image Value = lotGUID, DbType = System.Data.DbType.String });
    • 我刚刚编辑以添加更多列。你遇到了什么错误?
    • 抱歉回复晚了,这两天我一直在努力寻找替代方案。我明白了,我已经尝试过你给我的代码,然后我意识到我使用的是 System.data.sqlite 而不是 Microsoft.data.sqlite。目前我收到以下错误消息:“您需要调用 SQLitePCL.raw.SetProvider()。如果您使用的是捆绑包,则可以通过调用 SQLitePCL.Batteries.Init() 来完成。”在创建连接时。很抱歉给您带来了麻烦,我刚开始使用 c# 1 个月,仍在努力
    • @ChanJunLiang 没问题,我也遇到过这个问题,因为包名,我们是来学习和分享知识的?
    • 非常感谢 Leo,你救了我的命!
    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多