Python checking sql database column for value -


how 1 check entire column in sqlite database given value , if found set variable true

something like

hasvalue = 'false'  cur = con.cursor() cur.execute("select id column hasvalue = '1' limit 1;") ***if execute returned rows set hasvalue = true here***  if hasvalue == 'true':    else:    dosomethingelse 

how make hasvalue turn true if sql query returned , if returned 0 rows stay false?

basically want execute if in column equals 1

i'm little confused question. sql query suggests using table named column? if can ignore , assume have table named test has columns id (an int) , name (a string). query:

select id test name = 'something' 

would select rows have name set string 'something'.

in python be:

cur = con.cursor() cur.execute("select id test name = 'something' limit 1")  if cur.fetchone():     do_something() else:     do_something_else() 

the key here use cursor.fetchone() try , retrieve row cursor. if there no rows fetchone() return none, , none evaluates false when used condition in if statement.

you create function generalise:

def has_value(cursor, table, column, value):     query = 'select 1 {} {} = ? limit 1'.format(table, column)     return cursor.execute(query, (value,)).fetchone() not none  if has_value(cur, 'test', 'name', 'ranga'):     do_something() else:     do_something_else() 

this code constructs query given table, column, , value , returns true if there @ least 1 row required value, otherwise returns false.


Comments