<br>---------- Forwarded message ----------<br>From: Keith Hughitt <<a href="mailto:keith.hughitt@gmail.com">keith.hughitt@gmail.com</a>><br>To: <a href="mailto:python-list@python.org">python-list@python.org</a><br>Date: Wed, 18 Nov 2009 06:09:11 -0800 (PST)<br>
Subject: Inserting Unicode text with MySQLdb in Python 2.4-2.5?<br>Hi all,<br>
<br>
I ran into a problem recently when trying to add support for earlier<br>
versions of Python (2.4 and 2.5) to some database related code which<br>
uses MySQLdb, and was wondering if anyone has any suggestions.<br>
<br>
With later versions of Python (2.6), inserting Unicode is very simple,<br>
e.g.:<br>
<br>
    # -*- coding: utf-8 -*-<br>
    ...<br>
    cursor.execute('''INSERT INTO `table` VALUES (0,<br>
'Ångström'),...''')<br>
<br>
When the same code is run on earlier versions, however, the results is<br>
either garbled text (e.g. "àor "?" instead of "Å" in Python 2.5), or<br>
an exception being thrown (Python 2.4):<br>
<br>
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in<br>
position 60: ordinal not in range(128)<br>
<br>
So far I've tried a number of different things, including:<br>
<br>
    1. Using Unicode strings (e.g. u"\u212B")<br>
<br>
    2. Manually specifying the encoding using sys.setdefaultencoding<br>
('utf-8')<br>
<br>
    3. Manually enabling Unicode support in MySQLdb<br>
(use_unicode=False, charset = "utf8")<br>
<br>
...but no combination of any of the above resulted in proper database<br>
content.<br>
<br>
To be certain that the issue was related to Python/MySQLdb and not<br>
MySQL itself, I manually inserted the text and it worked just fine.<br>
Furthermore, when working in a Python console, both print "Å" and<br>
print u"\u212B" display the correct output.<br>
<br>
Any ideas? The versions of the MySQLdb adapter tested were 1.2.1<br>
(Python 2.4), and 1.2.2-10 (Python 2.5).<br>
<br>
Thanks!<br>
Keith<br>----<br><br>Hello Keithm,<br><br>Here is your answer...<br><br>I run on Python2.5, this syntax works fine for me -- a piece of my code:<br><br>        getMaxID_Query = """SELECT MAX(customerID)<br>
        FROM customer;"""<br><br>        self.cursorMySQL.execute(getMaxID_Query)        <br><br>Try to use: """ instead of ''' . It will solve your problem.<br><br>ThreaderSlash<br>
<br><br><br><br><br><input id="gwProxy" type="hidden"><input onclick="jsCall();" id="jsProxy" type="hidden"><div id="refHTML"></div>