Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentes Révision précédente Prochaine révision | Révision précédente | ||
python:sqlite3:start [2020/11/25 06:04] marclebrun [Connexion] |
python:sqlite3:start [2024/01/21 15:09] (Version actuelle) marclebrun |
||
---|---|---|---|
Ligne 4: | Ligne 4: | ||
* SQLite [[https://www.sqlite.org/docs.html]] | * SQLite [[https://www.sqlite.org/docs.html]] | ||
* Librairie Python : [[https://docs.python.org/2/library/sqlite3.html]] | * Librairie Python : [[https://docs.python.org/2/library/sqlite3.html]] | ||
+ | * [[https://www.sqlite.org/datatype3.html|Datatypes In SQLite]] | ||
+ | |||
+ | ===== Installation ===== | ||
+ | |||
+ | À partir de Python 2.5, **sqlite3** fait partie de la librairie | ||
+ | standard, il n'y a donc rien à installer. | ||
===== Connexion ===== | ===== Connexion ===== | ||
Ligne 31: | Ligne 37: | ||
''') | ''') | ||
</code> | </code> | ||
+ | |||
+ | ===== Version et migration de la DB ===== | ||
+ | |||
+ | Utilisation de **PRAGMA user_version** pour mettre à jour la structure | ||
+ | d'une base de données dès la connexion : | ||
+ | * [[https://groups.google.com/g/python-sqlite/c/brlzyZeySns]] | ||
+ | |||
===== Requêtes paramétrées ===== | ===== Requêtes paramétrées ===== | ||
+ | |||
+ | ==== INSERT ==== | ||
<code python> | <code python> | ||
Ligne 41: | Ligne 56: | ||
values | values | ||
(:name, :age, :size, :weight);""", { | (:name, :age, :size, :weight);""", { | ||
- | "name" : "Marc Lebrun", | + | "name" : "Albert Dupont", |
"age" : 49, | "age" : 49, | ||
"size" : 1.85, | "size" : 1.85, | ||
"weight": 92.5 | "weight": 92.5 | ||
}) | }) | ||
+ | | ||
+ | conn.commit() | ||
</code> | </code> | ||
+ | |||
+ | ==== SELECT ==== | ||
<code python> | <code python> | ||
cur = conn.cursor() | cur = conn.cursor() | ||
- | cur.execute("""select * from prople | + | cur.execute("""select * from people |
where name=:who and age=:age;""", { | where name=:who and age=:age;""", { | ||
- | "who": "Arnold", | + | "who": "Albert Dupont", |
- | "age": 73 | + | "age": 49 |
}) | }) | ||
+ | | ||
+ | # Obtenir une ligne du résultat sous forme de tuple | ||
+ | row = cur.fetchone() | ||
+ | |||
+ | # Obtenir toutes les lignes sous forme de liste de tuples | ||
+ | rows = cur.fetchall() | ||
+ | |||
+ | # Boucler sur le résultat directement | ||
+ | rows = cur.execute("...") | ||
+ | for row in rows: | ||
+ | ... | ||
</code> | </code> | ||