UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
iMath
redstone-cold at 163.com
Fri Dec 7 10:42:47 EST 2012
在 2012年12月6日星期四UTC+8下午7时07分35秒,Hans Mulder写道:
> On 6/12/12 11:07:51, iMath wrote:
>
> > the following code originally from http://zetcode.com/databases/mysqlpythontutorial/
>
> > within the "Writing images" part .
>
> >
>
> >
>
> > import MySQLdb as mdb
>
> > import sys
>
> >
>
> > try:
>
> > fin = open("Chrome_Logo.svg.png",'rb')
>
> > img = fin.read()
>
> > fin.close()
>
> >
>
> > except IOError as e:
>
> >
>
> > print ("Error %d: %s" % (e.args[0],e.args[1]))
>
> > sys.exit(1)
>
> >
>
> >
>
> > try:
>
> > conn = mdb.connect(host='localhost',user='testuser',
>
> > passwd='test623', db='testdb')
>
> > cursor = conn.cursor()
>
> > cursor.execute("INSERT INTO Images SET Data='%s'" % \
>
> > mdb.escape_string(img))
>
>
>
> You shouldn't call mdb.escape_string directly. Instead, you
>
> should put placeholders in your SQL statement and let MySQLdb
>
> figure out how to properly escape whatever needs escaping.
>
>
>
> Somewhat confusingly, placeholders are written as %s in MySQLdb.
>
> They differ from strings in not being enclosed in quotes.
>
> The other difference is that you'd provide two arguments to
>
> cursor.execute; the second of these is a tuple; in this case
>
> a tuple with only one element:
>
>
>
> cursor.execute("INSERT INTO Images SET Data=%s", (img,))
>
>
thanks,but it still doesn't work
>
> > conn.commit()
>
> >
>
> > cursor.close()
>
> > conn.close()
>
> >
>
> > except mdb.Error as e:
>
> >
>
> > print ("Error %d: %s" % (e.args[0],e.args[1]))
>
> > sys.exit(1)
>
> >
>
> >
>
> > I port it to python 3 ,and also change
>
> > fin = open("chrome.png")
>
> > to
>
> > fin = open("Chrome_Logo.png",'rb')
>
> > but when I run it ,it gives the following error :
>
> >
>
> > Traceback (most recent call last):
>
> > File "E:\Python\py32\itest4.py", line 20, in <module>
>
> > mdb.escape_string(img))
>
> > UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
>
> >
>
> > so how to fix it ?
>
>
>
> Python 3 distinguishes between binary data and Unicode text.
>
> Trying to apply string functions to images or other binary
>
> data won't work.
>
>
>
> Maybe correcting this bytes/strings confusion and porting
>
> to Python 3 in one go is too large a transformation. In
>
> that case, your best bet would be to go back to Python 2
>
> and fix all the bytes/string confusion there. When you've
>
> got it working again, you may be ready to port to Python 3.
>
>
>
>
>
> Hope this helps,
>
>
>
> -- HansM
More information about the Python-list
mailing list