如何使用Microsoft.Data.SQLite存储包含空字符的BLOB?

3

我正在尝试使用 Microsoft.Data.SQLite 2.2.6 在 SQLite 数据库中存储 BLOB。

这是我的做法:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.2</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="Microsoft.Data.SQLite" Version="2.2.6" />
    </ItemGroup>

</Project>

using Microsoft.Data.Sqlite;

namespace InsertBlobContainingNullCharacter
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var connection = new SqliteConnection("Data Source=Test.sqlite3"))
            {
                connection.Open();

                var create = connection.CreateCommand();
                create.CommandText = "CREATE TABLE IF NOT EXISTS test(file1 BLOB, file2 BLOB)";
                create.ExecuteNonQuery();

                var delete = connection.CreateCommand();
                delete.CommandText = "DELETE FROM test";
                delete.ExecuteNonQuery();

                var insert = connection.CreateCommand();
                insert.CommandText = "INSERT INTO test (file1, file2) VALUES (@file1, @file2)";
                insert.Parameters.AddWithValue("file1", new byte[] {0x31, 0x32, 0x33, 0x00, 0x34, 0x35, 0x36}).SqliteType = SqliteType.Blob;
                insert.Parameters.AddWithValue("file2", new byte[] {0x31, 0x32, 0x33, 0x34, 0x35, 0x36}).SqliteType = SqliteType.Blob;
                insert.ExecuteNonQuery();

                connection.Close();
            }
        }
    }
}

我正在存储一个包含空字符(0x00)的byte[]file1列中,但它被截断了。当我试图使用sqlite3工具读取该值时,我发现它恰好在空字符处被截断。如预期,file2列没有被截断:

$ sqlite3 Test.sqlite3 "SELECT file1 FROM test" | xxd
00000000: 3132 330a                                123.
$ sqlite3 Test.sqlite3 "SELECT file2 FROM test" | xxd
00000000: 3132 3334 3536 0a                        123456.

我做错了什么?我该如何将byte[]作为BLOB存储而不被截断?

1个回答

1
原来我对数据被截断的假设是错误的。数据完整存储,但sqlite3命令在显示结果时对其进行了截断。
使用HEX函数可以证明一切正常:
$ sqlite3 Test.sqlite3 "SELECT HEX(file1) FROM test"
31323300343536
$ sqlite3 Test.sqlite3 "SELECT HEX(file2) FROM test"
313233343536

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接