Python Glossary Русский

all Python 3sqlite3function

sqlite3.register_converter()

adapters and converters

Registers a function that turns a value read from a column of a declared type into a Python object. The function receives bytes.

Syntax

sqlite3.register_converter(typename, converter, /)

A converter stays silent until the connection is opened with detect_types=sqlite3.PARSE_DECLTYPES (or PARSE_COLNAMES): otherwise you get whatever is stored. Its argument is always bytes, not str, so call .decode(). It is not called for NULL. The name is matched case-insensitively against the first word of the column type, but SQLite also derives type affinity from that name: a DECIMAL column stores '1.10' as the number 1.1, so the converter gets b'1.1'.

Examples

import sqlite3
sqlite3.register_converter('point', lambda b: tuple(map(int, b.split(b';'))))
plain = sqlite3.connect(':memory:')
plain.execute('CREATE TABLE p(xy point)')
plain.execute("INSERT INTO p VALUES ('1;2')")
print(plain.execute('SELECT xy FROM p').fetchone())  # → ('1;2',) — без detect_types
plain.close()
conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute('CREATE TABLE p(xy POINT)')
conn.execute("INSERT INTO p VALUES ('1;2'), (NULL)")
print(conn.execute('SELECT xy FROM p').fetchall())  # → [((1, 2),), (None,)]
conn.close()
import sqlite3
from decimal import Decimal
sqlite3.register_converter('decimal', lambda b: Decimal(b.decode()))
conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute('CREATE TABLE p(price DECIMAL)')
conn.execute('INSERT INTO p VALUES (?)', ('1.10',))
print(conn.execute('SELECT price FROM p').fetchone())  # → (Decimal('1.1'),) — ноль потерян
conn.close()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy