我使用Python 2.7并在pyCharm中运行mysql.connector
鉴于这些例子,下面的cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name))
似乎应该有效。
但是,当我在pyCharm中写这行时,我收到此错误:
检查说:
如果我运行代码,我会收到此错误:
您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的'%s'附近使用正确的语法
以下是完整代码:
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')
注意,如果我在查询字符串中键入值,它一切正常,它只是不会让我使用参数。
答案 0 :(得分:4)
当你尝试执行查询时,你得到的错误来自mysql。传递给cursor.execute()
的查询参数需要是一个元组,您传递的是一个值。要创建具有单个元素的元组,您需要在元素后添加逗号:
cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name,))
否则mysql.connector
不会转义任何内容,并在查询中保留文字%s
。