我正在尝试使用 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
存储而不被截断?