如何在sqlite中找到二进制blob的长度(大小)

Pet*_*org 36 sqlite size blob

我有一个包含BLOB文件的sqlite表,但需要对blob进行大小/长度检查,我该怎么做?

根据我发现的一些文档,使用length(blob)将不起作用,因为length()仅适用于文本,并将在第一个NULL之后停止计数.我的实证检验证明了这一点.

我正在使用SQLite 3.4.2


更新:

因此,从SQLite 3.7.6开始,似乎length()函数返回正确的blob值 - 我检查了sqlite的各种更改日志,但没有看到更正的版本.

来自Sqlite 3.7.6:

payload_id|length(payload)|length(hex(payload))/2
1807913|194|194
1807914|171|171

文件被更改,以反映这一点.

length(X)   The length(X) function returns the length of X in characters if X is
            a string, or in bytes if X is a blob. If X is NULL then length(X) is
            NULL. If X is numeric then length(X) returns the length of a string 
            representation of X.

Jav*_*ier 41

没有这个问题,但你可以试试 length(hex(glob))/2

更新(2012年8月): 对于SQLite 3.7.6(2011年4月12日发布)及更高版本,length(blob_column)可以按预期方式处理文本和二进制数据.


小智 10

对我来说length(blob)工作得很好,给出了与其他相同的结果.

  • 对于二进制blob?这将违反SQLite文档,该文档将blob视为文本,因此length()只有在找到`\ 0`字符时才准确. (2认同)
  • http://www.sqlite.org/lang_corefunc.html 上的当前文档说“如果 X 是字符串,则 length(X) 函数以字符为单位返回 X 的长度,如果 X 是 blob,则以字节为单位返回 X 的长度。” (2认同)

Rei*_*ica 7

作为一个额外的答案,一个常见的问题是sqlite有效地忽略了表的列类型,因此如果将字符串存储在blob列中,它将成为该行字符串列.由于长度在字符串上的工作方式不同,因此它只返回最后0个字节之前的字符数.在blob列中存储字符串很容易,因为您通常必须显式转换以插入blob:

insert into table values ('xxxx'); // string insert
insert into table values(cast('xxxx' as blob)); // blob insert
Run Code Online (Sandbox Code Playgroud)

要获取存储为字符串的值的正确长度,可以将长度参数强制转换为blob:

select length(string-value-from-blob-column); // treast blob column as string
select length(cast(blob-column as blob)); // correctly returns blob length
Run Code Online (Sandbox Code Playgroud)

长度(十六进制(blob-column))/ 2工作的原因是十六进制不会在内部0个八位字节停止,并且生成的十六进制字符串不再包含0个八位字节,因此length返回正确的(完整)长度.