Steve Hanov
Steve Hanov

Reputation: 11584

How do you escape a binary file for sqlite3 in python?

The python sqlite3 documentation gives this example for inserting parameters into an SQL query.

for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

That's fine for text and numbers. What if one of the fields is a binary BLOB, such as a JPEG image? How does one insert a binary file?

Upvotes: 2

Views: 369

Answers (1)

MRAB
MRAB

Reputation: 20664

Insert binary data just as you would for any other type of field:

contents = open(image_path, "rb").read()
c.execute('insert into images values (?, ?)', (image_path, contents))

Upvotes: 2

Related Questions