3

I'd like to insert a string object containing binary data into a MySQL blob column. However, I keep getting MySQL syntax errors.

I made a small script for debugging purposes:

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)

Result (but not every time...)

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")

The problem apparently boils down to certain characters in the binary data which MySQL doesn't like. Is there a fail-safe way of putting binary data into the MySQL database?

4

2 回答 2

11

这样做,而不是:

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

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

于 2013-03-19T15:55:36.400 回答
1

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

于 2013-03-19T16:07:25.420 回答