kirtcathey
kirtcathey

Reputation: 343

Saving Binary Data To MySQLdb - Python

I have googled and searched this site, but nothing specific appears and cannot get this working. Here is the code:

    binData = ''.join(map(lambda x: chr(x % 256), attach.attcoll))

    sql_stmt = """INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattachment) \
    VALUES ('%s','%s','%s','%s','%s','%s') ON DUPLICATE KEY UPDATE filename='%s',fileextension='%s'""", attach.attno,\
attach.filename,attach.fileextension,attach.projNo,attach.procNo,binData,attach.filename,attach.fileextension

    try:
        cursor.execute(MySQLdb.escape_string(sql_stmt))
        conn.commit()

The attach.attcoll is data that comes in over JSON from an SQLite blob and java code on the client side. I then want to write binData to MySQL with MySQLdb, but keep getting a TypeError, and a return code of 500. Any ideas on how to fix this. I want to store binData into a MySQL blob.

Upvotes: 1

Views: 4438

Answers (1)

Jesse Cohen
Jesse Cohen

Reputation: 4040

Bunch of things here:

binData = ''.join(map(lambda x: chr(x % 256), attach.attcoll))
sql_stmt = """INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattachment)
VALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE filename=%s,fileextension=%s""" 

params = (attach.attno,attach.filename,attach.fileextension,attach.projNo,attach.procNo,binData,attach.filename,attach.fileextension)

cursor.execute(sql_stmt, params)
conn.commit()

A summary:

  1. Make sure you are connected to the db first (if you don't know how to do this, read the MySQLdb documentation)
  2. You don't want to escape your entire query, only the data parts, passing the statement and data separately to cursor.execute() means the cursor will escape it for you.
  3. Dont quote your '%s', MySQLdb does that for you as well.
  4. Is your database transactional (i.e. InnoDB), is that why you are using conn.commit(), it is not necessary if you aren't using a transactional engine.
  5. Without seeing how you've structured your db table I can't guarantee this will work. As practice, have you tried creating a really simple database table and practiced inserting into it with MySQLdb, just so you familiarize yourself with the API?

Upvotes: 1

Related Questions