Hans
Hans

Reputation: 21

Retrieving two variable columns from sqlite3 database with python

I am trying to get information from a database but I want to get information from two variable columns.

I have tried this:

def example(timeframe, stock):

    verloop = bm_cursor.execute("""SELECT ?, ? FROM barometer""", (timeframe, stock)).fetchall()
    for regel in verloop:
        print(regel)

hoping that it would select the columns that were defined in the two variables. But alas, this way I get a list of the two variables and not the information inside the columns.

Let's say

timeframe = "5_min"

stock = "APPL"

i was hoping it would be executed like:

bm_cursor.execute("""SELECT 5_min, APPL FROM barometer""", (timeframe, stock)).fetchall()

but that doesn't happen.

I did find something about using a format, but the way I understand it, i can only use it on one variable/column and not on both.

I.E.

def example(timeframe, stock):

    verloop = bm_cursor.execute("""SELECT ({}) FROM barometer""".format(timeframe)).fetchall()
    for regel in verloop:
        print(regel)

this works to get the values of one column, but how do I get the second one?

Upvotes: 1

Views: 48

Answers (1)

ilias-sp
ilias-sp

Reputation: 6685

the timeframe variable should be a string variable equal to the actual column name. stock too.

timeframe = "timeframe"
stock = "stock"

and the block:

verloop = bm_cursor.execute("""SELECT {}, {} FROM barometer""".format(timeframe, stock)).fetchall()
for regel in verloop:
    print(regel)

please note that the parentheses were removed in the SELECT <column1>, <column2> ... statement.

Upvotes: 1

Related Questions