【问题标题】:Is there a way to replace a NUL that got into a string in SQLite?有没有办法替换进入 SQLite 中的字符串的 NUL?
【发布时间】:2022-06-12 13:21:16
【问题描述】:

我有一个 Sqlite 数据库,它在某些字符串中获得了 NUL 字节。我想用 '\0' 替换那个 NUL 字节,以便我知道该字符串包含一个 NUL 字节,并且 NUL 字节后面的所有内容都是可见的。 这是我从工作中继承的数据库。我没有把这件事弄得一团糟,我只需要处理它。

我尝试了类似的方法:

 iif(instr(Message, char(0)) = 0
     , Message
     , substr(Message, 1, instr(Message, char(0)))
       || "\0"
       || substr(Message, instr(Message, char(0))-length(Message)+1)
 )

但似乎我实际上无法访问 NUL 之外的字符串。
看起来 substrlength 会将字符串视为 NUL 终止,并且不会转到实际字符串的末尾。我可以通过使用LENGTH(CAST(Message AS BLOB)) 获得实际字符串的长度(以字节为单位)(这很好,因为我们在 UTF8 中只使用了 7 位字符),但这不涉及substr,它不会过去NUL(向前(+ve 起始位置)或向后(-ve 起始位置))。

有没有办法解决这个问题?


顺便说一句,我知道 NUL 可以被剥离,但这会删除 NUL 之后的所有内容。可以在here 找到该信息。我就是从那里得到上述想法的。

我也试过了:

replace(Message, char(0), "\0")

这也没用。

【问题讨论】:

    标签: string sqlite nul


    【解决方案1】:

    您需要使用substr() 来获取 0 字节之前的部分,然后再次获取之后的部分 - 但这仅适用于 blob,而不适用于文本,因此需要强制转换:

    sqlite> CREATE TABLE foo(bar);
    sqlite> INSERT INTO foo VALUES ('apple' || char(0) || 'bacon');
    sqlite> SELECT * FROM foo;
    bar  
    -----
    apple
    sqlite> SELECT length(cast(bar AS BLOB)) FROM foo;
    length(cast(bar AS BLOB))
    -------------------------
    11                       
    sqlite> SELECT substr(bar, 1, instr(bar, char(0))) || '\0' || substr(cast(bar AS blob), instr(bar, char(0)) + 1) FROM foo;
    substr(bar, 1, instr(bar, char(0))) || '\0' || substr(cast(b
    ------------------------------------------------------------
    apple\0bacon                                                
    sqlite> 
    

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 2020-07-29
      • 2021-09-27
      • 1970-01-01
      • 2020-04-09
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多