4

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?

2 Answers 2

13

Do it this way, instead:

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

Instead of doing Python-level string formatting, this uses MySQL-specific formatting, including escaping characters that have special meaning to MySQL in strings that are to be embedded in queries.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this seems to work! I really don't understand the underlying principle though. Thanks!
Instead of doing Python-level string formatting, this uses MySQL-specific formatting, including escaping characters that have special meaning to MySQL in strings that are to be embedded in queries.
1

The error is not related to the formating of the string, but the an SQL syntax. So I guess the problem is with the SQL query itself, not the characters. Use query = '''INSERT INTO cheese (data) VALUES ('%s')''' % bd Where you enclose the string in question in a single quote.

1 Comment

I already tried different type of quotes in different combinations, so that wasn't the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.