100 words
1 minute
SQLite BLOB literals

SQLite BLOB literals#

I wanted to construct a string of SQL that would return a blob value:

select 'binary-data' as content, 'x.jpg' as content_filename

This was while writing a unit test for datasette-media - for issue #19. I used it in the test here.

The SQLite documentation for Literal values explains how to do this:

BLOB literals are string literals containing hexadecimal data and preceded by a single “x” or “X” character. Example: X’53514C697465’

In Python 3 you can generate the hexadecimal representation of any byte string using b'...'.hex()

So my solution looked like this:

jpeg_bytes = open("content.jpg", "rb").read()
sql = "select X'{}' as content, 'x.jpg' as content_filename".format(jpeg_bytes.hex())
SQLite BLOB literals
https://mranv.pages.dev/posts/sqlite-blob-literals/
Author
Anubhav Gain
Published at
2024-08-26
License
CC BY-NC-SA 4.0