I want to retrieve some data from a dbase. All the tables in it have the utf8_general_ci collation.
By the way, this is a .cgi file, so it is executed by means of an Ajax call.
I'm doing this to make the connection:
#!/home/mike/python_venvs/test_venv369/bin/python
...
conn = mysql.connector.connect( host='', database='test_kernel',
user='root', password='root',
charset='utf8', use_unicode=True )
...
query = ("SELECT * from invoices limit 2")
cursor.execute( query )
for x in cursor:
print( type( x )) # is a tuple, i.e. the row
for y in x:
print( type( y ) ) # the problem field prints "str"
if type( y ) == 'str':
y = y.encode( 'utf-8')
print( y )
On the encoding line above I get:
<class 'UnicodeEncodeError'> 'ascii' codec can't encode character '\xa3' in position 0: ordinal not in range(128)
With all the permutations I've tried I get the same thing. '\xa3', by the way, is the '£' character, non-ASCII.
I've tried many different approaches, found mainly here in SO: encode, decode, ... Nothing seems to work. I thought the str
type was Python 2... but this is definitely a Python3 program, something which I actually checked with sys.version_info[ 0 ]
!