在MySQL blob中插入python二进制字符串对象

时间:2013-03-19 15:53:24

标签: python mysql

我想将包含二进制数据的字符串对象插入到MySQL blob列中。但是,我不断收到MySQL语法错误。

我为调试目的制作了一个小脚本:

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数据库的故障安全方法?

2 个答案:

答案 0 :(得分:8)

这样做,而不是:

query = '''INSERT INTO cheese (data) VALUES (%s)'''
cur.execute(query, (bd,))

它不使用Python级别的字符串格式,而是使用特定于MySQL的格式,包括在要嵌入查询的字符串中转义对MySQL具有特殊含义的字符。

答案 1 :(得分:1)

错误与字符串的格式化无关,而与SQL语法有关。 所以我猜问题是SQL查询本身,而不是字符。 使用query = '''INSERT INTO cheese (data) VALUES ('%s')''' % bd将有问题的字符串括在单引号中。

相关问题