1

I try to build an sql query string with .format() and binary content (injections are no problem). The minimal example needs an example image in the same path.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

try:
    con = lite.connect(':memory:')

    cur = con.cursor()
    binary = lite.Binary(open("woman.jpg", "rb").read())

    cur.execute("CREATE TABLE 'Images' ('Data' BLOB)") 
    cur.execute("INSERT INTO Images(Data) VALUES (?)", (binary,) )

    query = "INSERT INTO Images(Data) VALUES ({0})".format(binary)
    cur.execute(query) # <- doesn't work obviously

    con.commit()    

except lite.Error, e:

    if con:
        con.rollback()

    print "Error %s:" % e.args[0]
    sys.exit(1)

finally:

    if con:
        con.close()  

Just like the insert image example from http://zetcode.com/db/sqlitepythontutorial/ but with .format() query generation

Is there a way to achieve this with .format()? I want to use a consistent way of inserting data into the db.

Thank you.

1 Answer 1

2

You can format you BLOB data as a BLOB LITERAL value according to the SQLite docs, e.g.

X'53514C697465'

The binary data can be encoded as a hex digit string ahd then be inserted using format.

with open(path, 'rb') as f:
    "X'{0}'".format(r.read().encode('hex'))
Sign up to request clarification or add additional context in comments.

2 Comments

Note also that the data must not be wrapped with Binary for this to work. binary = open("woman.jpg", "rb").read() works.
So the final correct way is: "X'{0}'".format(open(path, "rb").read().encode('hex') Thank you very much, too easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.