无法参数化列和表
如this SO answer中所述,无法参数化列和表。任何权威来源都可能没有记录的事实(我找不到一个,所以如果你知道一个,请编辑这个答案和/或上面链接的那个),而是通过人们尝试到底是什么而了解到的在问题中尝试。
动态插入列或表名的唯一方法是通过标准 python 字符串格式:
cur.execute("Select count(*) from {0}".format(table))
不幸的是,这为您打开了SQL 注入的可能性
白名单可接受的列/表名称
这个 SO 答案说明您应该使用白名单来检查可接受的表名。这就是你的样子:
import sqlite3
def RT():
conn = sqlite3.connect ("MyDB.db")
table = input("enter table name: ")
cur = conn.cursor()
if table not in ['user', 'blog', 'comment', ...]:
raise ... #Include your own error here
execute("Select count(*) from {0}".format(table))
for row in cur:
print str(row[0])
conn.close()
相同的 SO 答案警告直接接受提交的名称“因为验证和实际表可能不同步,或者您可能忘记检查。 ”意思是,您应该只自己派生表的名称。您可以通过明确区分接受用户输入和实际查询来做到这一点。这是您可能执行的操作的示例。
import sqlite3
acceptable_table_names = ['user', 'blog', 'comment', ...]
def RT():
"""
Client side logic: Prompt the user to enter table name.
You could also give a list of names that you associate with ids
"""
table = input("enter table name: ")
if table in acceptable_table_names:
table_index = table_names.index(table)
RT_index(table_index)
def RT_index(table_index):
"""
Backend logic: Accept table index instead of querying user for
table name.
"""
conn = sqlite3.connect ("MyDB.db")
cur = conn.cursor()
table = acceptable_table_names[table_index]
execute("Select count(*) from {0}".format(table))
for row in cur:
print str(row[0])
conn.close()
这可能看起来很无聊,但这保留了原始界面,同时解决了忘记检查白名单的潜在问题。验证和实际表仍然可能不同步;你需要编写测试来对抗它。