Skip to content
Advertisement

Using Python, how to return just one value instead of an entire row in an SQL query

I have a SQL database file which contains a multitude of columns, two of which are ‘GEO_ID’ and ‘MED_INCOME’. I am trying to retrieve just the ‘MED_INCOME’ column data using the associated ‘GEO_ID’. Here is what I thought would work:

import sqlite3 as db

def getIncome(censusID):
    conn = db.connect('census.db')
    c = conn.cursor()
    c.execute("SELECT 'MED_INCOME' FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
    response = c.fetchall()
    c.close()
    conn.close()
    return response

id = 60014001001
incomeValue = getIncome(id)
print("incomeValue: ", incomeValue)

Which results in:

incomeValue: [('MED_INCOME',)]

I thought that I had used this method before when attempting to retrieve the data from just one column, but this method does not appear to work. If I were to instead write:

c.execute("SELECT * FROM censusDbTable WHERE GEO_ID = %s" % (censusID)

I get the full row’s data, so I know the ID is in the database file.

Is there something about my syntax that is causing this request to result in an empty set?

Advertisement

Answer

Per @Ernxst comment, I adjusted the request to:

c.execute("SELECT MED_INCOME FROM censusDbTable WHERE GEO_ID = %s" % (censusID)

Removing the quotes around the column ID, which solved the problem.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement