Escape字符串Python for MySQL

时间:2010-09-01 10:24:00

标签: python mysql escaping

我使用Python和MySQLdb下载网页并将其存储到数据库中。我遇到的问题是我无法在数据库中保存复杂的字符串,因为它们没有被正确转义。

我是否可以使用Python中的函数来转义MySQL的字符串?我尝试使用'''(三重简单引号)和""",但它没有用。我知道PHP有mysql_escape_string(),在Python中类似吗?

感谢。

7 个答案:

答案 0 :(得分:83)

conn.escape_string()

请参阅MySQL C API函数映射:http://mysql-python.sourceforge.net/MySQLdb.html

答案 1 :(得分:53)

如果您使用他们的实现来构建SQL查询字符串而不是尝试构建自己的SQL查询字符串,MySQLdb库实际上会为您执行此操作。

不要这样做:

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

执行:

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

答案 2 :(得分:9)

>>> import MySQLdb
>>> example = r"""I don't like "special" chars ¯\_(ツ)_/¯"""
>>> example
'I don\'t like "special" chars \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf'
>>> MySQLdb.escape_string(example)
'I don\\\'t like \\"special\\" chars \xc2\xaf\\\\_(\xe3\x83\x84)_/\xc2\xaf'

答案 3 :(得分:1)

使用sqlalchemy的文字功能删除特殊字符的解释:

请注意使用下面的函数text("your_insert_statement")。它的作用是与sqlalchemy沟通,传入的字符串中的所有问号和百分号都应被视为文字。

import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re

engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
     % ("your_username", "your_password", "your_hostname_mysql_server:3306",
     "your_database"),
     pool_size=3, pool_recycle=3600)

conn = engine.connect()

myfile = open('access2.log', 'r')
lines = myfile.readlines()

penguins = []
for line in lines:
   elements = re.split('\s+', line)

   print "item: " +  elements[0]
   linedate = datetime.fromtimestamp(float(elements[0]))
   mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")

   penguins.append(text(
     "insert into your_table (foobar) values('%%%????')"))

for penguin in penguins:
    print penguin
    conn.execute(penguin)

conn.close()

答案 4 :(得分:0)

安装sqlescapy软件包:

pip install sqlescapy

然后您可以在原始查询中转义变量

from sqlescapy import sqlescape

query = """
    SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)

答案 5 :(得分:0)

解决此问题的另一种方法是在python中使用mysqlclient时使用类似的方法。

假设您要输入的数据是这样的<ol><li><strong style="background-color: rgb(255, 255, 0);">Saurav\'s List</strong></li></ol>。它同时包含双qoute和单引号。

您可以使用以下方法对引号进行转义:

statement =“”“更新聊天集html ='{}'”“” .format(html_string.replace(“'”,“ \\\'”))

注意:需要三个\字符以转义无格式python字符串中的单引号。

答案 6 :(得分:-4)

{!a}适用于ascii(),因此转义了引号甚至表情符号之类的非ASCII字符。 这是一个例子

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 docs