On 12/6/2012 5:07 AM, iMath wrote:
the following code originally from
http://zetcode.com/databases/mysqlpythontutorial/
within the "Writing images" part .
import MySQLdb as mdb
Not part of stdlib. 'MySQLdb' should be in the subject line to get
attention of someone who is familiar with it. I am not.
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))
From the name, I would expect that excape_string expects text. From the
error, it seems to specifically expect utf-8 encoded bytes. After
decoding, I expect that it does some sort of 'escaping'. An image does
not qualify as that sort of input. If escape_string takes an encoding
arg, latin1 *might* 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 ?
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list