UnicodeEncodeError: 'charmap' with 'Ö', 'Ç' etc.

I connect to MySQL and extract user names containing "...", "," Ş ", etc. It works fine with MySQL or PHP, but an error occurs in Python 2.6.8. Here is my code:

#C:\Python27\Lib\encodings
#-*- coding: utf-8 -*-

conn = MySQLdb.Connect(host="localhost", user="root", passwd="mypass", db="mydb", charset="utf8", init_command="SET NAMES UTF8")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("select * from users");
tmpDict=cursor.fetchallDict()
print tmpDict[0]['NAME'].decode('utf8')

I expect "Ömer Şirin" here, but instead get the following error:

'ascii' codec cannot encode character u '\ xd6' at position 0: serial number not in range (128)

How can i fix this?

+4
source share
2 answers

There are two errors and two problems:

  • UnicodeEncodeError: 'charmap' with 'Ö', 'Ç' etc.
  • 'ascii' u '\ xd6' 0: (128)

type(tmpDict[0]['NAME']) == unicode, :

>>> u'\xd6'.decode('utf-8') #XXX BROKEN, DO NOT DO IT!!!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

, , u'\xd6' Unicode, , Python ('ascii'). - .decode('utf-8') - Unicode ( Python 3, AttributeError , Unicode).

"UnicodeEncodeError:" charmap ", , Unicode Windows. print u'\xd6'. , win-unicode-console.

+2

MySQL UTF-8 Unicode Python.

>>> type(tmpDict[0]['NAME'])
<type 'unicode'>

tmpDict[0]['NAME'] . , StackOverflow

0

Source: https://habr.com/ru/post/1615727/


All Articles