credo che il più efficiente "Esiste" query è solo fare un count
:
sqlq = "SELECT COUNT(1) FROM settings WHERE status = '1'"
xcnx.execute(sqlq)
if xcnx.fetchone()[0]:
# exists
invece di chiedere al database per eseguire qualsiasi operazione di conteggio sui campi o righe, si sta solo chiedendo di restituisce 1 o 0 se il risultato produce corrispondenze. Questo è molto più efficiente che restituisce i record effettivi e conta il numero di client lato perché salva la serializzazione e la deserializzazione su entrambi i lati e il trasferimento dei dati.
In [22]: c.execute("select count(1) from settings where status = 1")
Out[22]: 1L # rows
In [23]: c.fetchone()[0]
Out[23]: 1L # count found a match
In [24]: c.execute("select count(1) from settings where status = 2")
Out[24]: 1L # rows
In [25]: c.fetchone()[0]
Out[25]: 0L # count did not find a match
count(*)
sta per essere lo stesso di count(1)
. Nel tuo caso perché stai creando una nuova tabella, mostrerà 1 risultato. Se hai 10.000 corrispondenze, sarebbe 10000. Ma tutto quello che ti interessa nel test è se NON è 0, quindi puoi eseguire un test di verità bool.
Aggiornamento
In realtà, è ancora più veloce di appena usare il conteggio delle righe, e nemmeno recuperare i risultati:
In [15]: if c.execute("select (1) from settings where status = 1 limit 1"):
print True
True
In [16]: if c.execute("select (1) from settings where status = 10 limit 1"):
print True
In [17]:
Questo è anche il modo ORM di Django fa un queryObject.exists()
.
Vuoi solo per verificare che sia possibile stabilire una connessione con il database o che sia possibile creare tabelle e inserire dati correttamente? – jdi
No so che posso collegarmi creare e inserire, ho solo bisogno di sapere come controllare e verificare se esiste un record. –