UTF8 invalid codec in python

Asked

Viewed 89 times

-1

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 running the script I get this error:

inserir a descrição da imagem aqui

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

1 answer

2


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

In your case in the error it is possible to see that this occurs in the character 'Ã' and to search for the character 0xe3 will realize that he is the hexa para 'a'. That’s why the message:

can’t Decode byte 0xe3.

Add on bank connection charset='utf8':

db = MySQLdb.connect(host="xxx.xxx.x.xx", user="xxxxx", passwd="xxxxxxx", db="xxxxxxx", charset='utf8')
  • is in ANSI. How I change in python IDLE 3.7?

  • I found that the database problem well, because one of the variables uses ~, how can I solve?

  • @Beginner, edit your question or open another one with more code details and connection to BD. It will be easier to help you.

  • I edited the question with the code with the connection to the database and the loop. After if only has the API for sending the sms

Browser other questions tagged

You are not signed in. Login or sign up in order to post.