【问题标题】:PyMySQL - Using a string as cursor.execute argument [duplicate]PyMySQL - 使用字符串作为 cursor.execute 参数[重复]
【发布时间】:2018-11-11 00:16:20
【问题描述】:

我的问题涉及在下面的cursor.execute 中传递一个字符串

import pymsyql
import json

connection = pymysql.connect(
        host='localhost', user='u_u_u_u_u',
        password='passwd', db='test',
        charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
)

def get_data(table):
    try:
        with connection.cursor() as cursor:
            sql = """
                SELECT * FROM %s;
            """
            cursor.execute(sql, (table,))
            result = cursor.fetchall()
            return json.dumps([dict(ix) for ix in result])

    except (TypeError, pymysql.err.ProgrammingError) as error:
        print(error)
    finally:
        pass

get_data('table_1')

connection.close()

我得到了错误

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 ''table_1'' at line 1")

似乎execute 不希望将字符串作为参数传递;当我直接输入一个字符串时,比如cursor.execute(sql, ('table_1',)),我得到了同样的错误。

我对导致问题的原因感到困惑,双引号 ''table_1'' 令人困惑。谁能告诉我这里发生了什么?

【问题讨论】:

  • 很遗憾,您不能以这种方式指定表名。您必须将表名format() 输入到查询中,并且您有责任对其进行清理。

标签: python sql pymysql


【解决方案1】:

您不能将表名作为参数传递,唉。您必须将其放入查询字符串中:

        sql = """
            SELECT * FROM `{0}`;
        """.format(table)
        cursor.execute(sql)

【讨论】:

  • 我们都表达了同样的观点,即你不能这样做。为什么不能真正实现?
  • @roganjosh 。 . .您只能将常量作为参数传递。不是标识符、函数名、运算符等。
  • 对不起,我不清楚。在您回答说同样的话之前,我已经在答案下发表了评论。这是一个常见问题,我们的回复都说“不幸”/“唉”。我的问题是为什么它不能在语法中得到支持,因为它显然具有价值?
  • @roganjosh 。 . .因为存储查询的一个目的是缓存执行计划。您需要所有这些信息来编译查询。
  • 我认为@roganjosh 更多是出于感性的立场; “为什么”的问题可能是修辞性的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 2021-08-10
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多