- 此问题在此处已有答案**:
(13个答案)
How to use variables in SQL statement in Python?(5个答案)
六年前关闭了。
代码应该基于Python环境中用户的输入执行查询(而不是在sql查询中)。例如,变量是在Python环境中定义的,在table name = customers
的原始输入中,我希望查询打印表customers的列名。
但是,下面的代码报告了语法错误。如果我删除反斜杠和内引号,它将报告no such column: table_name
。看起来值customers
没有被传递到查询中,查询将table_name
读取为字符串。
帮帮忙。谢谢
import sqlite3
def ask_column(db_name, table_name):
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute('SELECT sql FROM sqlite_master WHERE type = \'table\' And name = \'table_name\'')
print c.fetchall()
conn.close()
db_name = raw_input("Please type the database name : ")
table_name = raw_input("Please type the table name: ")
ask_column(db_name, table_name)
1条答案
按热度按时间jljoyd4f1#
你可以使用参数替换来完成这个操作。当使用Python's sqlite3 module时,用问号(
?
)替换你的参数值,并提供一个值的 * 元组**。Python会自动处理替换,并转义值以限制SQL注入的风险。下面是一个例子:首先,创建一个表:
现在插入一些值:注意
?
字符是如何用作值的占位符的:下面是一个查询(注意,我们将值作为元组传递,即使只有一个值):