0

我必须在 python sqlite3 上编写一个函数来计算表的行数。问题是用户应该在函数执行后输入该表的名称。到目前为止,我有以下内容。但是,一旦执行,我不知道如何将变量(表)与函数“连接”。任何帮助都会很棒。谢谢

def RT():
    import sqlite3
    conn= sqlite3.connect ("MyDB.db")
    table=input("enter table name: ")
    cur = conn.cursor()
    cur.execute("Select count(*) from  ?", [table])
    for row in cur:
        print str(row[0])
    conn.close()
4

1 回答 1

0

无法参数化列和表

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

这可能看起来很无聊,但这保留了原始界面,同时解决了忘记检查白名单的潜在问题。验证和实际表仍然可能不同步;你需要编写测试来对抗它。

于 2016-04-25T15:13:16.693 回答