· 6 years ago · Nov 17, 2019, 05:40 PM
1import sqlite3
2import logging
3import csv
4import sys
5import os
6from datetime import datetime
7
8
9
10path_csv=("./data.csv")
11path_db=("./batabase.sqlite3")
12path_log=("./logs.log")
13
14def verifcsv(fichier_csv):
15 if not os.path.exists(fichier_csv):
16 logging.debug("Fichier CSV inexistant, fermeture du programme")
17 print("Erreur, le fichier CSV nommé ""%s"" inexistant, verifiez le repertoire courant "% fichier_csv)
18 exit(1)
19 else:
20 logging.debug("Fichier CSV valide")
21
22
23def verifdb(fichier_sqlite):
24 if not os.path.exists(fichier_sqlite):
25 logging.debug("La base de sonnées %s n'existe pas, création d'une nouvelle base de données" % fichier_sqlite)
26 else:
27 logging.debug("Fichier de base de données deja existant, fermeture du programme")
28 print("Erreur, le fichier portant le nom ""%s"" existe deja "% fichier_sqlite)
29 exit(1)
30
31
32
33def veriflog(fichier_log):
34 if os.path.exists(fichier_log):
35 logging.debug("le fichier de log deja existant")
36 else:
37 logging.debug("le fichier de log n'existe pas, creation de celui ci")
38
39
40logging.debug("Creating table")
41def createtab(cursor):
42 cursor.execute('''
43 CREATE TABLE IF NOT EXISTS automobile(
44 adresse_titulaire text,
45 nom text,
46 prenom text,
47 immatriculation text,
48 date_immatriculation text,
49 vin text,
50 marque text,
51 denomination_commerciale text,
52 couleur text,
53 carroserie text,
54 categorie text,
55 cylindree int,
56 energie int,
57 places int,
58 poids int,
59 puissance int,
60 type text,
61 variante text,
62 version int
63 );
64 ''')
65 connection.commit()
66
67
68def insertion_bdd(cursor,path_csv):
69 with open(path_csv) as csvfile:
70 lecteur = csv.DictReader(csvfile, delimiter=';')
71 to_db = [(row['adresse_titulaire'],row['nom'],row['prenom'],row['immatriculation'],row['date_immatriculation'],row['vin'] ,row['marque'] ,row['denomination_commerciale'] ,row['couleur'] ,row['carroserie'],row['categorie'] ,row['cylindree'] ,row['energie'] ,row['places'],row['poids'],row['puissance'],row['type'] ,row['variante'] ,row['version'] ) for row in lecteur]
72 cursor.executemany("INSERT INTO automobile (adresse_titulaire,nom,prenom,immatriculation,date_immatriculation,vin,marque,denomination_commerciale,couleur,carroserie,categorie,cylindree,energie,places,poids,puissance,type,variante,version) VALUES (?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", to_db)
73
74
75
76
77logging.basicConfig(format ='%(asctime)s : %(levelname)s : import.py : %(message)s',filename='logs.log',level=logging.DEBUG) #configuration du module logging
78logging.debug("Debut programme")
79
80
81if __name__ =='__main__':
82
83
84
85 verifcsv(path_csv)
86 verifdb(path_db)
87 veriflog(path_log)
88
89 logging.debug("Connection a la base de données")
90 connection=sqlite3.connect(path_db)
91 cursor=connection.cursor()
92
93 createtab(cursor)
94 insertion_bdd(cursor,path_csv)
95
96
97
98
99
100connection.commit()
101cursor.close()