How to retrieve a value from a SQLite3 table by column name and matching row value

304 Views Asked by At

I have a table that looks like this (summarized, the first row is the column names):

'hand_total', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'A'
('5', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H')
('6', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H')
('7', 'H', 'D', 'D', 'D', 'D', 'H', 'H', 'H', 'H', 'H')
('8', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'H', 'H')
('9', 'H', 'D', 'D', 'D', 'D', 'H', 'H', 'H', 'H', 'H')
('10', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'H', 'H')
('11', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'H')
('12', 'H', 'H', 'S', 'S', 'S', 'H', 'H', 'H', 'H', 'H')
('13', 'S', 'S', 'S', 'S', 'S', 'H', 'H', 'H', 'H', 'H')

I want to able to use a python variable to pick a value from this table by the header name and the values present in the 'hand_total' column. For example, if I want a value where the '3' column and the row with hand_total=='11' intersect, I would expect to return with the value 'D'. But no matter what I try I can't seem to get my sqlite3 queries to return what I'm expecting.

I have attempted

cur == conn.cursor()
cur.execute("SELECT 3 FROM test_table")
results = cur.fetchall() 

I'm expecting the above to return to me all of the column values from the column titled '3'. But the results I get end up just showing

[(3,), (3,), (3,), (3,) ....] 

until all length of db

1

There are 1 best solutions below

3
On

If a column name is not an identifier, escape it with double quotes (ANSI SQL), backticks (like MySQL), or square brackets (like SQL-Server).

cur.execute("""SELECT "3" FROM test_table WHERE hand_total = 11""")