我知道过去曾问过这个问题,但彻底的搜索似乎并没有解决我的问题。我可能只是错过了一些简单的东西,因为我是mysql提供的Python-mysql连接器的新手。
我有一个访问mysql数据库的Python脚本,但是我在从查询中删除引号方面遇到了问题。这是我的代码:
import mysql.connector
try:
db = mysql.connector.connect(user='root', password='somePassword', host='127.0.0.1', database='dbName')
cursor = db.cursor()
query = "select * from tags where %s = %s"
a = 'tag_id'
b = '0'
cursor.execute(query, (a, b))
print cursor
data = cursor.fetchall()
print data
except mysql.connector.Error as err:
print "Exception tripped..."
print "--------------------------------------"
print err
cursor.close()
db.close()
我的数据库设置正确(我很快就会证明)。
这个程序的输出是:
MySQLCursor: select * from tags where 'tag_id' = '0'
[]
然而,当我将查询更改为不使用变量时,例如:
cursor.execute("select * from tags where tag_id = 0")
然后我的输出变为:
MySQLCursor: select * from tags where tag_id = 0
[(0, u'192.168.1.110')]
对我而言,这意味着我的Cursor查询之间的唯一区别是引号。
如何从查询中删除它们?
提前致谢。
答案 0 :(得分:1)
我改变了两件重要的事情:
b = '0'
更改为b = 0
,因此最终为数字而不是带引号的字符串。 (这部分很容易解决。)下面的完整代码,但如果列名是用户输入,请再次注意!
import mysql.connector
def escape_column_name(name):
# This is meant to mostly do the same thing as the _process_params method
# of mysql.connector.MySQLCursor, but instead of the final quoting step,
# we escape any previously existing backticks and quote with backticks.
converter = mysql.connector.conversion.MySQLConverter()
return "`" + converter.escape(converter.to_mysql(name)).replace('`', '``') + "`"
try:
db = mysql.connector.connect(user='root', password='somePassword', host='127.0.0.1', database='dbName')
cursor = db.cursor()
a = 'tag_id'
b = 0
cursor.execute(
'select * from tags where {} = %s'.format(escape_column_name(a)),
(b,)
)
print cursor
data = cursor.fetchall()
print data
except mysql.connector.Error as err:
print "Exception tripped..."
print "--------------------------------------"
print err
cursor.close()
db.close()
答案 1 :(得分:0)
我在使用pymysql时遇到了类似的问题,并显示了我的工作代码here,希望这会有所帮助。
我所做的是 覆盖类'pymysql.connections.Connection'中的转义方法,该方法显然会在字符串周围添加“'”。
更好地显示了我的代码:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()