我试图将用户输入的结果传递到SQL查询中,如下所示:
def select_rows(conn):
table_choice = input("Choose a table: ")
cur = conn.cursor()
cur.execute("SELECT * FROM %s", table_choice)
rows = cur.fetchall()
for row in rows:
print(row)
但是我得到这个错误:
Database Path: C:\Users\Morgan\Desktop\SQL\chinook.db
Choose a table: album
Traceback (most recent call last):
File "C:\Users\Morgan\Desktop\SQL\SQL.py", line 27, in <module>
select_rows(conn)
File "C:\Users\Morgan\Desktop\SQL\SQL.py", line 20, in select_rows
cur.execute("SELECT * FROM %s", table_choice)
sqlite3.OperationalError: near "%": syntax error
有什么建议吗?
答案 0 :(得分:2)
您也可以使用f字符串:
cur.execute(f"SELECT * FROM {table_choice}")
但是请注意用户的输入和查询。您应该编写一个函数来验证输入。
答案 1 :(得分:1)
您需要先格式化查询再执行...:
cur.execute("SELECT * FROM {}".format(table_choice))
答案 2 :(得分:-1)
cur.execute("SELECT * FROM ?", (table_choice,))