Remarques sur l'utilisation de SQLite en Python C'est un mémorandum.
sample.py
import sqlite3
from contextlib import closing
dbname = "sample.db"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
query = '''drop table if exists User'''
c.execute(query)
conn.commit()
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
query = '''create table if not exists
User(id integer primary key, name varchar(32))'''
c.execute(query)
conn.commit()
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
query = ''' insert into User (id, name) values (?,?)'''
user = (1, "Yamashita")
c.execute(query, user)
conn.commit()
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
query = ''' insert into User (id, name) values (?,?)'''
user = [
(2, "Kinoshita")
,(3, "Hasegawa")
]
c.executemany(query, user)
conn.commit()
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
query = "select * from User"
for row in c.execute(query):
print(row)
with closing(sqlite3.connect(dbname)) as conn: Lors de l'utilisation de sqlite, commit () et close () sont requis après l'exécution de la requête. En utilisant la fermeture de contextlib, vous pouvez empêcher l'omission de la description close () de la connexion
c.executemany(query, user) Vous pouvez utiliser executemany () pour écrire plusieurs insertions à la fois, en passant une liste de taples comme arguments.
Recommended Posts