Menu

Problem storing binary data

Help
Alex Haan
2006-08-22
2012-09-19
  • Alex Haan

    Alex Haan - 2006-08-22

    I have searched and tried several things for too long, so I hope someone can tell me what stupid thing i forget to do..

    I have a simple mysql table, with id (integer) and data (blob) fields.

    I read in a (binary, linux) file and want to store it in the database as such. But i just cant get past the following error:

    Traceback (most recent call last):
    File "test.py", line 14, in ?
    c.execute(query)
    File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 146, in execute
    query = query.encode(charset)
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 614: ordinal not in range(128)

    ==============================
    script:

    import os
    import MySQLdb

    db = MySQLdb.connect(db="[db]", user="[username]", passwd="[password]")
    c = db.cursor()

    fd = open("file", 'rb')
    data = fd.read()

    query = "INSERT INTO torrent_filedata (id, data) VALUES ('%d', '%s')" \ % (9999, MySQLdb.escape_string(data))
    c.execute(query)

    c.close()
    db.close()

    Also, i have been using MySQLdb.escape_string(). But the docs say i should use connection.escape_string(). I tried to understand how i should actually implement that but didnt manage to do so.

     
    • Alex Haan

      Alex Haan - 2006-08-22

      doh..
      Debian 1:3.3.5-13
      Python 2.4.4c0
      MySQLdb 1.2.1_p2

       
    • Alex Haan

      Alex Haan - 2006-08-22

      Thank you for your swift response. A simple tip, and it works flawlessly now.

      Hmm, and after reading the docs i can't say that that information wasn't in there. But if you know what to look for it is easier to find :)

      Doesn't say anything about not needing the escape_string() function, but it sure keeps the code cleaner.

       
    • Andy Dustman

      Andy Dustman - 2006-08-22

      I wish people would stop things the hard and wrong way (i.e. what you're doing) and do it the easy and right way:

      query = "INSERT INTO torrent_filedata (id, data) VALUES (%s, %s)"
      parameters = (9999, data)
      c.execute(query, parameters)

      Do NOT use escape_string(). Period. escape_string() is only if you are using _mysql directly. If you are using MySQLdb, it does all the escaping for you.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.