数据库
首页 > 数据库> > 在Python 2.7中将参数化查询与mysql.connector一起使用

在Python 2.7中将参数化查询与mysql.connector一起使用

作者:互联网

我在0C中使用Python 2.7在pyCharm中运行

我需要使用显示为herealso here的参数化查询

给定这些示例,下面的cursor.execute(“ SELECT * FROM automaticReports WHERE pythonFunctionName =%s”,(function_name))应该可以工作.

但是,当我在pyCharm中编写此行时,出现此错误:

enter code here

检查说:

enter image description here

如果运行代码,则会出现此错误:

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.

标签:mysql-connector,mysql-connector-python,python,mysql
来源: https://codeday.me/bug/20191026/1937757.html