UTF8 invalid codec in python [closed]

0

I'm using this code in the script:

#! /usr/bin/env python
# coding: utf8
import MySQLdb

db = MySQLdb.connect(host="xxx.xxx.x.xx", user="xxxxx", passwd="xxxxxxx", db="xxxxxxx")    

cursor = db.cursor()

cursor.execute("SELECT DataConsulta, Dias, HoraConsulta, HoraSaida, nome, Consulta, centrodb.LocalConsulta.Descricao, Contato FROM centrodb.RegistoConsultas LEFT OUTER JOIN centrodb.LocalConsulta ON centrodb.LocalConsulta.Id = centrodb.RegistoConsultas.'Local' LEFT OUTER JOIN centrodb.UtentesCons ON centrodb.UtentesCons.codigoutente = centrodb.RegistoConsultas.Utente LEFT OUTER JOIN centrodb.DiasSemana ON centrodb.DiasSemana.Id = centrodb.RegistoConsultas.DiaSemana")

myresult = cursor.fetchall()

for linha in myresult:
 DataConsulta = linha[0]
 Dias = linha[1]
 HoraConsulta = linha[2]
 HoraSaida = linha[3]
 nome = linha[4]
 Consulta = linha[5]
 Descricao = linha[6]
 Contato = linha[7]

 today = datetime.date.today()
 data = today + datetime.timedelta(days=7)

 if DataConsulta == data:
 ...

But when I run the script I get this error:

The problem is the characters that exist in the database table with ~ , how can I solve the problem?

    
asked by anonymous 12.12.2018 / 14:58

1 answer

3

This is because you are actually reading data that is not in UTF-8.

In your case in the error you can see that this occurs in the character 'Ã' and if you search for the character 0xe3 you will notice that it is the hexa for 'ã'. So the message:

  

can not decode byte 0xe3.

Add to the database connection charset='utf8' :

db = MySQLdb.connect(host="xxx.xxx.x.xx", user="xxxxx", passwd="xxxxxxx", db="xxxxxxx", charset='utf8')
    
12.12.2018 / 17:08