在 Python 2.7 中使用带有 mysql.connector 的参数化查询

Use parameterized query with mysql.connector in Python 2.7

我在 pyCharm

中使用 Python 2.7 和 mysql.connector 运行ning

我需要使用如图所示的参数化查询 here and also here

鉴于这些示例,下面的 cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name)) 似乎应该有效。

然而,当我在 pyCharm 中写入这一行时,我得到了这个错误:

检查说:

如果我 运行 代码,我得到这个错误:

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 '%s' at line 1

完整代码如下:

class DatabaseManager():
    def get_report_settings_for_function_named(self, function_name):
        """
        Get the settings for a given report from the database based on the name of the function that was called
        to process the report

        This is how we get the, email subject and email addresses to send the report to

        :param function_name: The name of the function that was called to process the report
        :type function_name: str.
        :returns:  array -- the settings row from the database.

        """
        cnx = mysql.connector.connect(**config)
        cursor = cnx.cursor(dictionary=True)

        cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name))

        row = cursor.fetchone()
        cursor.close()
        cnx.close()

        print cursor.statement

        return row

print DatabaseManager().get_report_settings_for_function_named('process_elation_credit_report')

我在这里做错了什么?这是旧语法吗?我不这么认为...

请注意,如果我将值键入查询字符串,一切正常,只是不让我使用参数。

您收到的错误来自 mysql 尝试执行查询时。传递给 cursor.execute() 的查询参数需要是一个元组,您传递的是单个值。要创建具有单个元素的元组,您需要在元素后添加一个逗号:

cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name,))

否则 mysql.connector 不会转义任何内容并在查询中保留文字 %s