我想将包含二进制数据的字符串对象插入到MySQL blob列中。但是,我不断收到MySQL语法错误。在MySQL blob中插入python二进制字符串对象
我为调试用小脚本:(不是每一次,但...)
import MySQLdb
import array
import random
conn = MySQLdb.connect(host="localhost", user="u", passwd="p", db="cheese")
cur = conn.cursor()
a = array.array('f')
for n in range(1,5):
a.append(random.random())
bd = a.tostring()
print type(bd) # gives str
query = '''INSERT INTO cheese (data) VALUES (%s)''' % bd
cur.execute(query)
结果
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '?fJ\x95<=
\xad9>\xf3\xec\xe5>)' at line 1")
的问题显然是归结于二进制数据的某些字符, MySQL不喜欢。是否有将二进制数据放入MySQL数据库的自动防故障方式?
是的,这似乎工作!我真的不明白基本原则。谢谢! – 2013-03-19 17:32:39
不使用Python级别的字符串格式,而是使用特定于MySQL的格式,包括对嵌入查询的字符串中具有特殊含义的字符进行转义。 – djc 2013-03-20 10:23:01