← retour aux snippets

sqlite3: récupérer des lignes comme des dicts (Row)

Activer row_factory=sqlite3.Row pour accéder aux colonnes par nom.

python db #sqlite-3#dict

objectif

Activer row_factory=sqlite3.Row pour accéder aux colonnes par nom.

code minimal

import sqlite3
con = sqlite3.connect(":memory:")
con.execute("create table t(id integer, name text)")
con.execute("insert into t values(1,'a')")
con.row_factory = sqlite3.Row
row = con.execute("select * from t").fetchone()
print(row["name"] == "a")  # attendu: True
con.close()

utilisation

import sqlite3
con = sqlite3.connect(":memory:"); con.row_factory = sqlite3.Row
con.execute("create table t(x int)"); con.execute("insert into t values(3)")
r = con.execute("select x from t").fetchone()
print(dict(r)["x"] == 3); con.close()

variante(s) utile(s)

import sqlite3
print(hasattr(sqlite3, "Row"))

notes

  • Row se comporte comme un mapping indexable par nom ou index.
  • Combinez avec parameters ? pour éviter l’injection SQL.