简单 "CREATE" 或 "DROP TABLE" 因 PyMySQL 和参数替换而失败

Simple "CREATE" or "DROP TABLE" fails with PyMySQL and parameter replacement

我基本上使用以下代码删除现有 table 使用 Python 3.6 和 PyMySQL,使用 MySQL 5.7 数据库:

connection = pymysql.connect(
    host=host,
    user=username,
    password=password,
    db=database,
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

table_name = "video_playback_statistics"
sql = "DROP TABLE IF EXISTS %s"
params = (table_name,)

with connection.cursor() as cursor:
    cursor.execute(sql, params)

我收到以下错误:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''video_playback_statistics'' at line 1"

我已经成功执行了其他具有更多参数的更复杂的 SQL 语句,但是这个简单的语句不起作用。

当我 运行 没有参数化的 SQL 命令时,它工作正常:

cursor.execute('DROP TABLE IF EXISTS video_playback_statistics')

我查看了以下问题:

但这些类型的查询似乎工作正常。

我也看到了这个:

但是这里直接把table名字写进了字符串

显然 table 名称或列名称的参数化是不可能的,根据 this comment。由于某种原因,适配器为该值插入了两个双引号,这会导致语法错误。

两种可能的解决方案是:

  1. 参数使用反斜杠转义:

    sql = "DROP TABLE IF EXISTS `%s`"
    
  2. 使用Python字符串格式:

    sql = "DROP TABLE IF EXISTS {}".format(table_name)
    

对于值(例如在 INSERTWHERE 语句中),您仍应使用参数化。