在运行时将 table 名称添加到 SQL 查询

Adding table name to SQL query at runtime

我写了一个如下的方法:

def add(self,table_name, tc_no, file_no):
    self._cursor.execute("select HastaId from {}".format(table_name)," where TC=%s and FileNo=%s",(tc_no,file_no))
    row = self._cursor.fetchone()
    return row

我收到一个错误

TypeError: execute() takes at most 2 positional arguments (3 given)

我知道 format() 中的错误。我该如何使用它?

你的想法是对的。查询参数只能表示列 values,不能表示列或 table names

因此您 需要使用字符串格式将 table 名称插入 SQL 命令文本,然后使用查询参数提供值对于 WHERE 子句。

因此,这样的结构将不起作用:

crsr.execute(
        "select HastaId from %s where TC=%s and FileNo=%s",
        (table_name, tc_no, file_no))

但这会起作用

crsr.execute(
        "select HastaId from [{}] where TC=%s and FileNo=%s".format(table_name),
        (tc_no, file_no))