title: Insert python binary string object in MySQL blob
body: <p>I'd like to insert a string object containing binary data into a MySQL blob column. However, I keep getting MySQL syntax errors. </p>
  
  <p>I made a small script for debugging purposes:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Result (but not every time...)</p>
  
  <pre><code>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&lt;=  
  \xad9&gt;\xf3\xec\xe5&gt;)' at line 1")
  </code></pre>
  
  <p>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?</p>