Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert binary data into sqlite3 database in bash?

I want to insert binary data(png,jpg,gif,etc) into a sqlite3 database within a bash script.
I use the standalone binary sqlite3. How can I write the SQL statement?
Thanks for your help.

like image 554
kev Avatar asked Apr 27 '12 15:04

kev


People also ask

Can binary data be stored in SQLite?

sqlite-utils can now insert data from binary files, and datasette-media can serve content over HTTP that originated as binary BLOBs in a database file.

What is BLOB data type in SQLite?

A blob is a SQLite datatype representing a sequence of bytes. It can be zero or more bytes in size. SQLite blobs have an absolute maximum size of 2GB and a default maximum size of 1GB. An alternate approach to using blobs is to store the data in files and store the filename in the database.

How do I create a DB file in SQLite?

In SQLite, the sqlite3 command is used to create a new database. Syntax: sqlite3 DatabaseName. db.

How do I connect to a SQLite database?

Select SQLite from the list. Give a Connection name for your own internal reference. For Database , click Choose a File and then select the database file on your local machine to which you want to connect. Hit Connect and you're all set!


1 Answers

As I mentioned in the comment on @sixfeetsix's answer, inserting the data is only half the problem. Once it's in, you'll need to get it back out. We can use xxd for this.

#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 
like image 75
David Souther Avatar answered Oct 14 '22 20:10

David Souther