user808996 user808996 - 4 months ago 8
SQL Question

SQLite query with Python

I'm trying to use Python to do an SQLite query. I can get the desired result in SQLite using

SELECT Four FROM keys2 WHERE One = B


How do I do this in Python?

I am trying

c = conn.cursor()

print "Opened database successfully";
x = c.execute("SELECT Four FROM keys2 WHERE One = B")
print x

conn.close()


But I get the message "sqlite3.OperationalError: no such column: B". I'm trying to select the entry under column 4 where the one column is B. I have tried several methods to no avail.

Answer

Supply the value using parametrized SQL:

x = c.execute("SELECT Four FROM keys2 WHERE One = ?", "B")

The problem with the SQL you posted is that the value B must be quoted. So

x = c.execute("SELECT Four FROM keys2 WHERE One = 'B'")

would also have worked, but it is better to always use parametrized SQL (to guard against SQL injection) and let sqlite3 do the quoting for you.