Regex 使用Python 2.7在MySQL数据库中插入原始文本

Regex 使用Python 2.7在MySQL数据库中插入原始文本,regex,python-2.7,mysql-python,Regex,Python 2.7,Mysql Python,我正在尝试将使用re模块解析的文本插入mysql数据库。问题是mysql正在读取解析文本中的引号(即6英寸高跟鞋),并向我发出语法错误的错误消息。当解析文本中没有引号时,以下代码起作用: import re import MySQLdb as mysql f = open("All/text.txt", "rb") string = f.read() requirements = re.findall(r"text :(.*?)text", string, re.DOTALL) requi

我正在尝试将使用re模块解析的文本插入mysql数据库。问题是mysql正在读取解析文本中的引号(即6英寸高跟鞋),并向我发出语法错误的错误消息。当解析文本中没有引号时,以下代码起作用:

import re
import MySQLdb as mysql 

f = open("All/text.txt", "rb")
string = f.read()

requirements = re.findall(r"text :(.*?)text", string, re.DOTALL)
requirements = requirements[0]
requirements = str(requirements)#Parse out the requirements in between the two text delimiters

print requirements

host = "localhost"
usernm = "root"
password = "Password"
database = "test"


dbConnection = mysql.connect(host=host, user=usernm, passwd=password, db=database, local_infile = True)
cursor = dbConnection.cursor()


sql = """INSERT INTO test (requirements) VALUES ("%s")"""%requirements#Write the parsed text being held in the requirements variable into the test table, requirements columns

cursor.execute(sql)


dbConnection.commit()
cursor.close()
这里的问题是,如果我正在解析的文本文件中有引号,那么它将失败,因为mySQL正在读取引号

import re
import MySQLdb as mysql 

f = open("All/text.txt", "rb")
string = f.read()

requirements = re.findall(r"text :(.*?)text", string, re.DOTALL)
requirements = requirements[0]
requirements = str(requirements)#Parse out the requirements in between the two text delimiters

print requirements

host = "localhost"
usernm = "root"
password = "Password"
database = "test"


dbConnection = mysql.connect(host=host, user=usernm, passwd=password, db=database, local_infile = True)
cursor = dbConnection.cursor()


sql = """INSERT INTO test (requirements) VALUES ("%s")"""#Write the parsed text being held in the requirements variable into the test table, requirements columns

cursor.execute(sql, (requirements))



dbConnection.commit()
cursor.close()
我将需求移到游标内。执行,但不幸的是,这会给我一条错误消息:

cursor.execute(sql,(requirements))文件“C:\Python27\lib\site packages\MySQLdb\cursors.py”,第187行,在 执行 query=query%tuple([db.literal(item)用于args中的项])TypeError:在字符串格式化过程中并非所有参数都已转换

我希望能够将从文本文件中解析的所有字符输入到mysql表中,并将原始文本(希望能够轻松地转义整个字符串)输入到mysql表中

我是python新手,完全迷路了,非常感谢您的帮助。谢谢-Benipy

Replace cursor.execute(sql,(需求)) 在…上
cursor.execute(sql,(requirements,)

在字符串格式化过程中?格式化的字符串在进入变量后是否以某种方式被插入?如果是这种情况,则必须在format语句中使用之前转义双引号(
\”
)。