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

时间:2015-06-26 18:28:13

标签: 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)
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中移动了要​​求但不幸的是,这给了我一条错误消息:

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

我希望能够处理从文本文件中解析出来的所有字符,并输入原始文本(希望很容易地将整个字符串转义)到mysql表中。

我是python的新手,完全迷失了,非常感谢这里的一些帮助。谢谢 - Benipy

1 个答案:

答案 0 :(得分:0)

替换     cursor.execute(sql,(requirements)) 上     cursor.execute(sql,(requirements,))