Python checking sql database column for value
<p>How would one check an entire column in sqlite database for a given value and if found set a variable to true</p>

<p>something like</p>

<pre><code>hasvalue = 'false'

cur = con.cursor()
cur.execute("SELECT id FROM column WHERE hasvalue = '1' LIMIT 1;")
***IF execute returned rows set hasvalue = true here***

if hasvalue == 'true':
   do something
else:
   dosomethingelse
</code></pre>

<p>How would I make hasvalue turn to true if the sql query returned with something and if it returned 0 rows stay false?</p>

<p>Basically I want to execute something ONLY if something in a column equals 1</p>

<p>I'm a little confused by your question. The SQL query suggests that you are using a <em>table</em> named <code>column</code>? If I can ignore that and assume you have a table named <code>test</code> which has columns <code>id</code> (an int) and <code>name</code> (a string). Then the query:</p>

<pre><code>SELECT id FROM test where name = 'something'
</code></pre>

<p>would select all rows that have <code>name</code> set to the string <code>'something'</code>.</p>

<p>In Python this would be:</p>

<pre><code>cur = con.cursor()
cur.execute("SELECT id FROM test where name = 'something' LIMIT 1")

if cur.fetchone():
    do_something()
else:
    do_something_else()
</code></pre>

<p>The key here is to use <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.fetchone" rel="nofollow"><code>cursor.fetchone()</code></a> which will try and retrieve a row from the cursor. If there are no rows <code>fetchone()</code> will return <code>None</code>, and <code>None</code> evaluates to <code>False</code> when used as a condition in an <code>if</code> statement.</p>

<p>You could create a function to generalise:</p>

<pre><code>def has_value(cursor, table, column, value):
    query = 'SELECT 1 from {} WHERE {} = ? LIMIT 1'.format(table, column)
    return cursor.execute(query, (value,)).fetchone() is not None

if has_value(cur, 'test', 'name', 'Ranga'):
    do_something()
else:
    do_something_else()
</code></pre>

<p>This code constructs a query for the given table, column, and value and returns <code>True</code> if there is at least one row with the required value, otherwise it returns <code>False</code>.</p>

python database sqlite