Python MySQL-转义引号 [英] Python mySQL - escaping quotes

查看:186
本文介绍了Python MySQL-转义引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在本网站上以各种方式看到了这个问题,但是没有一个能够准确地解决我的问题.

I have seen this question asked in various ways on this website, but none of them exactly addressed my issue.

我有一个带单引号的sql语句,并且在使用它进行数据库查询之前尝试使用推荐的做法.所以声明就像

I have an sql statement with single quotes inside it, and am trying to use recommended practices before making database queries with it. So the statement is like

val2="abc 'dostuff'" 
sql="INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s,'%s')" %(val1, val2)
a_cursor.execute(sql)

但是,当我运行它时,我得到了.

However, when I run this, I get..

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 'dostuff'.

我做错了什么? 非常感谢 努布尔(Nupur)

What am I doing wrong? Thanks very much Nupur

推荐答案

使用参数而不是字符串插值来确保数据库连接器正确地转义了您的值:

Use parameters instead of string interpolation to ensure that your values are properly escaped by the database connector:

sql = "INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s, %s)"
a_cursor.execute(sql, (val1, val2))

mysqldb sql参数样式使用与python字符串格式化操作符相同的语法,这有点令人困惑.

The mysqldb sql parameter style uses the same syntax as used by the python string formatting operator, which is a little confusing.

这篇关于Python MySQL-转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆