【问题标题】:Insert Raw Text in MySQL db using Python 2.7使用 Python 2.7 在 MySQL 数据库中插入原始文本
【发布时间】:2015-09-13 19:12:46
【问题描述】:

我正在尝试将已使用 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 item in args]) TypeError: 在字符串格式化期间并非所有参数都被转换

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

我是 python 新手,完全迷路了,非常感谢这里的一些帮助。谢谢 - 贝尼皮

【问题讨论】:

  • 在字符串格式化期间?格式化的字符串在进入变量后是否以某种方式被插值?如果是这种情况,您必须先转义双引号(""\"),然后才能在格式语句中使用。

标签: regex python-2.7 mysql-python


【解决方案1】:

替换 cursor.execute(sql,(要求)) 在 cursor.execute(sql, (requirements,))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 2015-03-10
    • 2021-08-13
    • 1970-01-01
    • 2014-07-09
    • 2014-05-11
    相关资源
    最近更新 更多