1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import sqlite3
import os
BDD = './inventaire.db'
creerBDD = not os.path.isfile(BDD)
connexion = sqlite3.connect(BDD)
cur = connexion.cursor()
if creerBDD :
cur.execute(
'''CREATE TABLE CATEGORIES(
cat_id INTEGER PRIMARY KEY AUTOINCREMENT,
cat_nom TEXT UNIQUE NOT NULL)'''
)
cur.execute(
'''CREATE TABLE ITEMS(
item_id INTEGER PRIMARY KEY AUTOINCREMENT,
cat_id INT,
item_nom TEXT,
item_quantite INT,
FOREIGN KEY(cat_id) REFERENCES CATEGORIES(cat_id))'''
)
connexion.commit()
with open('fichier', 'r') as f :
for line in f :
item, quantite, cat = line.rstrip().split(':')
try :
cur.execute(
'INSERT INTO CATEGORIES(cat_nom) VALUES(?)',
(cat,)
)
catId = cur.lastrowid
# La catégorie existe déjà (unique)
except sqlite3.IntegrityError :
r = cur.execute('SELECT cat_id FROM CATEGORIES WHERE cat_nom=?', (cat,))
catId = r.fetchone()[0]
cur.execute(
'INSERT INTO ITEMS(cat_id, item_nom, item_quantite) VALUES(?, ?, ?)',
(catId, item, quantite,)
)
connexion.commit() |
Partager