如何在bash中将二进制数据插入sqlite3数据库?

kev*_*kev 6 sql sqlite binary bash

我想在bash脚本中将二进制数据(png,jpg,gif等)插入到sqlite3数据库中.
我使用独立的二进制文件sqlite3.我该如何编写SQL语句?
谢谢你的帮助.

Dav*_*her 9

正如我在@ sixfeetsix的回答中提到的那样,插入数据只是问题的一半.一旦它进入,你需要把它拿回来.我们可以使用xxd.

#A nice hubble image to work with.
echo 'http://asd.gsfc.nasa.gov/archive/hubble/Hubble_20th.jpg' > imageurl.txt
image=imageurl.txt
curl $image > image.jpg

#Insert the image, using hexdump to read the data into SQLite's BLOB literal syntax.
echo "create table images (image blob);" | sqlite3 images.db
echo "insert into images (image) values(x'$(hexdump -ve '1/1 "%0.2X"' image.jpg)');" | sqlite3 images.db 2>&1

#Select just the one image, then use xxd to convert from hex back to binary.
echo "select quote(image) from images limit 1 offset 0;" | sqlite3 images.db  | tr -d "X'" | xxd -r -p > newimage.jpg
eog newimage.jpg 
Run Code Online (Sandbox Code Playgroud)


小智 5

这是一种方法.test.jpg在编辑为sqlite的二进制文字格式后,该文件将插入foo到数据库的表中:foodbhexdump

[someone@somewhere tmp]$ sqlite3 foodb "create table foo (bar blob);"
[someone@somewhere tmp]$ echo "insert into foo values (X'`hexdump -ve '1/1 "%.2x"' test.jpg`');" | sqlite3 foodb
Run Code Online (Sandbox Code Playgroud)

编辑

在这里我们看到数据以"全保真"存储,因为.jpg文件可以恢复:

[somneone@somewhere tmp]$ sqlite3 foodb "select quote(bar) from foo;" | perl -ne 's/([0-9a-f]{2})/print chr hex $1/gie' > bla.jpg 
[somneone@somewhere tmp]$ ll *.jpg
-rw-rw-r-- 1 someone someone 618441 Apr 28 16:59 bla.jpg
-rw-rw-r-- 1 someone someone 618441 Apr 28 16:37 test.jpg
[someone@somewhere tmp]$ md5sum *.jpg 
3237a2b76050f2780c592455b3414813  bla.jpg
3237a2b76050f2780c592455b3414813  test.jpg
Run Code Online (Sandbox Code Playgroud)

此外,这种方法节省空间,因为它使用sqlite的BLOB类型存储.jpg.它不使用例如base64编码对图像进行字符串化.

[someone@somewhere tmp]$ ll foodb 
-rw-r--r-- 1 someone someone 622592 Apr 28 16:37 foodb
Run Code Online (Sandbox Code Playgroud)