sqlite - 是否可以将sqlite中的 '0'字符保存为文本

标签 sqlite system.data.sqlite

我在 sqlite 表中有一个带有\0 字符和文本字段的 UTF 字符串。
当我尝试将字符串插入表文本字段然后从数据库中读取它时,我注意到字符串值在\0 字符后被截断。

问题: 是否可以在 \0 之后在 sqlite 中保存/恢复此类字符串而不会丢失数据?

代码片段:

 public static void IssueWith0Character()
    {
        const string sql = "DROP TABLE IF EXISTS SomeTable;" +
                           "CREATE TABLE SomeTable (SomeField TEXT not null);"
                           + "INSERT INTO SomeTable (SomeField) Values ( :value )";

        var csb = new SQLiteConnectionStringBuilder
                      {DataSource = "stringWithNull.db", Version = 3};

        // string with '0' character
        const string stringWithNull = "beforeNull\0afterNull";

        using (var c = new SQLiteConnection(csb.ConnectionString))
        {
            c.Open();

            using (var cmd = c.CreateCommand())
            {
                var p = new SQLiteParameter(":value", DbType.String) {Value = stringWithNull};
                cmd.CommandText = sql;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();
            }

            using (var cmd = c.CreateCommand())
            {
                cmd.CommandText = "SELECT SomeField FROM SomeTable;";
                var restoredValue = (string) cmd.ExecuteScalar();
                Debug.Assert(stringWithNull == restoredValue);
            }
        }
    }    

UPDATE #1 看起来问题出在阅读阶段。数据库文件中至少存在字符串的“afterNull”部分。

更新 #2 这被认为是 System.Data.SQLite 错误 (<1.04.84)。 http://system.data.sqlite.org/index.html/tktview/3567020edf12d438cb7cf757b774ff3a04dc381e

最佳答案

在 SQLite 中,\0 字符被认为是无效的。

虽然可以将这样的字符串放入数据库(使用各种函数的指针+长度形式),但许多对字符串进行操作的函数在遇到\0 时就会停止。因此,documentation 说:

The result of expressions involving strings with embedded NULs is undefined.



如果您确实需要使用空字节存储数据,则应将其存储为 blob ( DbType.Binary )。

关于sqlite - 是否可以将sqlite中的 '0'字符保存为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15230477/

相关文章:

javascript - Sencha Touch 2 的大型离线存储

java - 返回已完成和待处理任务的计数

python - 使用 python sqlite 在同一事务中选择和更新

java - 我该从哪里开始这个 Android 项目呢?

c# - 使用 LINQ 访问表中的第一个元素时出现 SQLite 错误

c# - SQLite.Net 问题与 BeginTransaction

java - 在 Eclipse (Android) 中连接数据库 (SQLITE) 文件

sqlite - 使用 System.Data.Sqlite 时为 "Cannot find entry point sqlite3_open_v2 in DLL sqlite3"

c# - 使用 C# 提高大数据导入 SQLite 的性能

c# - SQLite:.Net 比原生慢很多?