pythonsqldatabase

SQL SELECT from table name supplied by a variable


Whenever I try the code below, I get near "?": syntax error I tried multiple things including prepping it into a variable

Is this possible in python? Or am I thinking in the wrong direction?

import sqlite3

sqlite_file = 'DATABASE.db'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
word = ()
question = int(input("What would you like to see?"))
if question == 1:
    word = ("Batchnumbers")
if question == 2:
    word = ("Worker IDs")
c.execute('SELECT * FROM ?', (word))
    data = c.fetchall()
    for x in range(len(data)):
        print(data[x])

Solution

  • Indeed use this line of code word =

    c.execute('SELECT * FROM "{}"'.format(word))