简体   繁体   中英

Can I use python to simplify an SQLite query involving all columns?

I am working on a function which takes an string input, and then returns the name of the column in a database which contains that string.

con =sqlite3.connect('library.db')
cur = con.cursor()
data=cur.execute('''SELECT * FROM table1''')
def search_word():
word = input("Input search word")
for column in data.description:
    cur.execute('''SELECT ? FROM table1 WHERE ?=?''',(str(column[0]),str(column[0]),str(word),))
    output = cur.fetchone()
    print(output)

search_word()

In the above function, inputting print(column[0]) successfully prints the name of every column in the table, so I know that part of the function works. However, when I run the function with aa search word I know is in the database, every iteration produces "None" as an output. What am I doing wrong?

There are a couple of stack overflow issues that address this already. See here and here . In short, column names are not a security issue, so if you want to do anything dynamic with them, you need to use regular python string operations for that part and use parameter binding for just the values. Something like this should work.

for column in data.description:
    query = f'''SELECT {column[0]} FROM table1 WHERE {column[0]} = ?'''
    cur.execute(query,(str(word),))
    output = cur.fetchone()
    print(output)

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