Python Glossary Русский

all Python 3sqlite3function

sqlite3.register_adapter()

adapters and converters

Registers a function that turns an object of your type into a value SQLite understands (int, float, str, bytes, None) when it is bound to a query.

Syntax

sqlite3.register_adapter(type, adapter, /)

Without an adapter, a Decimal or your own class in the parameters raises ProgrammingError 'type ... is not supported'. Registration is global for the whole process, not per connection. The built-in date and datetime adapters are deprecated since 3.12 and emit DeprecationWarning: register your own, such as date.isoformat. The reverse step on reading is register_converter.

Examples

# Python 3.11+
import sqlite3
from decimal import Decimal
conn = sqlite3.connect(':memory:')
try:
    conn.execute('SELECT ?', (Decimal('1.10'),))
except sqlite3.ProgrammingError as e:
    print(e)  # → is not supported — имя типа в тексте: 'decimal.Decimal', с 3.15 'Decimal'
sqlite3.register_adapter(Decimal, str)
print(conn.execute('SELECT ?, typeof(?)', (Decimal('1.10'),) * 2).fetchone())  # → ('1.10', 'text')
conn.close()
import datetime
import sqlite3
sqlite3.register_adapter(datetime.date, datetime.date.isoformat)
conn = sqlite3.connect(':memory:')
print(conn.execute('SELECT ?', (datetime.date(2024, 5, 1),)).fetchone())  # → ('2024-05-01',) — без DeprecationWarning
conn.close()

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy