如何在Python3中将输入转义到MySQL数据库? [英] How can I escape the input to a MySQL db in Python3?
问题描述
如何在Python3中转义MySQL数据库的输入? 我正在使用PyMySQL,并且工作正常,但是当我尝试执行以下操作时:
How can I escape the input to a MySQL db in Python3? I'm using PyMySQL and works fine, but when I try to do something like:
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = '{}'".format(request[1]))
如果字符串具有'
或"
,则将不起作用.我也尝试过:
it won't work if the string has '
or "
. I also tried:
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = %s",request[1])
此问题是库(PyMySQL)使用Python2.x的格式语法%
,该语法不再起作用.
我也找到了可能的解决方案
The problem with this is that the library (PyMySQL) uses the formatting syntax for Python2.x, %
, that doesn't work anymore.
I also found this possible solution
conn.escape_string()
在此处中,但是我不知道在何处添加此代码. 这就是我得到的:
in here, but I don't know where to add this code. This is all I got:
import pymysql
import sys
conn = pymysql.connect( host = "localhost",
user = "test",
passwd = "",
db = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = {}".format(request[1]))
result = cursor.fetchall()
cursor.close()
conn.close()
我解决了!在PyMySQL中,正确的方法是这样的:
I solved it! In PyMySQL the right way is like this:
import pymysql
import sys
conn = pymysql.connect(host="localhost",
user="test",
passwd="",
db="test")
cursor = conn.cursor()
text = conn.escape(request[1])
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = {}".format(text))
cursor.close()
conn.close()
text = conn.escape(request[1])
行是转义代码的地方.在PyMySQL代码中找到它.在那里,输入request[1]
.
Where the text = conn.escape(request[1])
line is what escapes the code. Found it inside PyMySQL code. There, request[1]
is the input.
推荐答案
已解决.在PyMySQL中,正确的方法是这样的:
Solved. In PyMySQL the right way is like this:
import pymysql
import sys
conn = pymysql.connect(host="localhost",
user="test",
passwd="",
db="test")
cursor = conn.cursor()
text = conn.escape(request[1])
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = {}".format(text))
cursor.close()
conn.close()
text = conn.escape(request[1])
行是转义代码的地方.在PyMySQL代码中找到它.在那里,输入request[1]
.
Where the text = conn.escape(request[1])
line is what escapes the code. Found it inside PyMySQL code. There, request[1]
is the input.
这篇关于如何在Python3中将输入转义到MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!