在Python 2.7中将参数化查询与mysql.connector一起使用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Python 2.7中将参数化查询与mysql.connector一起使用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1707字,纯文字阅读大概需要3分钟。
内容图文
我在0C中使用Python 2.7在pyCharm中运行
给定这些示例,下面的cursor.execute(“ SELECT * FROM automaticReports 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.
内容总结
以上是互联网集市为您收集整理的在Python 2.7中将参数化查询与mysql.connector一起使用全部内容,希望文章能够帮你解决在Python 2.7中将参数化查询与mysql.connector一起使用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。