【问题标题】:Adding table name to SQL query at runtime在运行时将表名添加到 SQL 查询
【发布时间】:2016-01-01 01:29:25
【问题描述】:

我写了一个方法如下:

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() 最多接受 2 个位置参数(给定 3 个)

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

【问题讨论】:

    标签: python pymssql


    【解决方案1】:

    你的想法是对的。查询参数只能表示列,不能表示列或表名称

    因此您确实需要使用字符串格式将表名插入到 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))
    

    【讨论】:

      猜你喜欢
      • 2011-02-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      相关资源
      最近更新 更多