简体   繁体   中英

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])

Query parameters can only be used to supply column values , not table or column names . If you need to supply a table name you will have to use dynamic SQL, eg,

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

Note that this approach is vulnerable to SQL injection issues, so you really should consider mitigating those, eg, ensuring that word does not contain double-quote characters that would cause errors (or worse).

确实使用这行代码字=

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM