计算 Pysqlite3 中的行数

Count number of rows in Pysqlite3

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

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

无法参数化列和表

this SO answer 中所述,无法参数化列和 table。一个可能没有被任何权威来源记录的事实(我找不到一个,所以如果你知道一个,请编辑这个答案 and/or 上面链接的那个),而是通过人们尝试完全了解的问题中尝试了什么。

动态插入列或 table 名称的唯一方法是通过标准 python 字符串格式:

cur.execute("Select count(*) from {0}".format(table))

不幸的是,这为您打开了 SQL 注入的可能性

白名单接受table Column/Table 名称

说明您应该使用白名单来检查 acceptable table 名称。这就是你的样子:

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 回答警告直接接受提交的名称“因为验证和实际 table 可能会不同步,或者您可能会忘记检查。”意思是,您应该只自己导出 table 的名称。您可以通过明确区分接受用户输入和实际查询来做到这一点。这是您可以执行的操作的示例。

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

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