Pour vérifier si un élément existe déjà dans une table sous sqlite3, il existe plusieurs possibilités (voir la très bonne réponse sur stackoverflow: How to check the existence of a row in SQLite with Python?). Le plus simple est d'utiliser la fonction fetchall, comme ceci:
QueryCurs.execute("Select * from Clients where Ville = 'Fourmies' ")if len( QueryCurs.fetchall() ) == 0:print "Existe: Oui"else:print "Existe: Non"
Exemple complet en partant du précédent article:
import sqlite3CreateDataBase = sqlite3.connect('MyDataBase.db')QueryCurs = CreateDataBase.cursor()def CreateTable():QueryCurs.execute('''CREATE TABLE Clients(id INTEGER PRIMARY KEY, Nom TEXT,Rue TEXT,Ville TEXT, Region TEXT, Note REAL)''')def AddEntry(Nom,Rue,Ville,Region,Note):QueryCurs.execute('''INSERT INTO Clients (Nom,Rue,Ville,Region,Note)VALUES (?,?,?,?,?)''',(Nom,Rue,Ville,Region,Note))CreateTable()AddEntry('Toto','Rue 1','Lille','Nord',105.2)AddEntry('Bill','Rue 2','Fourmies','Nord',105.2)AddEntry('Ben','Rue 3','Lille','Nord',105.2)AddEntry('Paul','Rue 4','Lille','Nord',105.2)CreateDataBase.commit()QueryCurs.execute('SELECT * FROM Clients')for i in QueryCurs:print "\n"for j in i:print j#----- check the existence of a row:print '----------'print "check the existence of a row:"print ' 'QueryCurs.execute("Select * from Clients where Ville = 'Fourmies' ")if len( QueryCurs.fetchall() ) == 0:print "Ville Fourmies Existe: Non"else:print "Ville Fourmies Existe: Oui"QueryCurs.execute("Select * from Clients where Ville = 'Lyon' ")if len( QueryCurs.fetchall() ) == 0:print "Ville Lyon Existe: Non"else:print "Ville Lyon Existe: Oui"QueryCurs.close()
donne ici
1TotoRue 1LilleNord105.22BillRue 2FourmiesNord105.23BenRue 3LilleNord105.24PaulRue 4LilleNord105.2----------check the existence of a row:Ville Fourmies Existe: OuiVille Lyon Existe: Non
Recherches associées
| Liens | Site |
|---|---|
| How to check the existence of a row in SQLite with Python? | stackoverflow |
| sqlite3 — DB-API 2.0 interface for SQLite databases | Python doc |
| SQLite Python tutorial | SQLite Python tutorial |
| Python check if exists in SQLite3 | stackoverflow |
| Python and SQLite: Check if an item exists in a database? | stackoverflow |
| Valid query to check if row exists in SQLite3 | stackoverflow |
| cursor.rowcount always -1 in sqlite3 in python3k | stackoverflow |
