Python Glossary Русский

Python 3.11+sqlite3term

sqlite3.Blob

connections and queries

A file-like object that reads and writes a BLOB value in the database piece by piece. It is created with Connection.blobopen().

Syntax

with conn.blobopen(table, column, rowid) as blob: blob.write(data)

A Blob cannot be resized: writing past the end raises ValueError, so reserve the space up front with INSERT ... VALUES (zeroblob(n)). The row is chosen by rowid, not by a WHERE clause. It pays off for large binary data you do not want in memory at once; for small values a plain SELECT returning bytes is simpler. Open it with with so the handle gets closed.

Examples

import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE files(data BLOB)')
conn.execute('INSERT INTO files VALUES (zeroblob(5))')
with conn.blobopen('files', 'data', 1) as blob:
    blob.write(b'hello')
    print(len(blob), blob[1:3])  # → 5 b'el'
print(conn.execute('SELECT data FROM files').fetchone())  # → (b'hello',)
conn.close()
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE files(data BLOB)')
conn.execute("INSERT INTO files VALUES (x'0102')")
with conn.blobopen('files', 'data', 1) as blob:
    try:
        blob.write(b'abc')
    except ValueError as e:
        print(e)  # → data longer than blob length
conn.close()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy