unicode error python when import fields with accented text

2

I have an error when I execute the command below, it generates the text file correctly when I import database texts without stress, but when there is some accent appears the error:

  

File "C: /Users/ti/Desktop/report.py", line 17, in doQuery rows = cur.fetchall () UnicodeDecodeError: 'ascii' codec can not decode byte 0xc3 in position 272: ordinal not in range (128)

hostname = '192.168.0.50'
username = 'aasd'
password = 'asdasd'
database = 'db1'


def doQuery( conn ):
    cur = conn.cursor()
    comando_sql = """SELECT os.numos, 
             ccusto.nomecc,prest.nomeprest,equip.especifica
             from osmanut as os 
             left join cadcc as ccusto on os.codccserv = ccusto.codcc 
             left join cadprest as prest on os.prestsolic = prest.codprest 
             left join cadeqman as equip on os.codequipa = equip.codequipa 
             where codtecos = '007' and CAST(os.dataconclu AS DATE) = '2017-07-05' order by os.numos"""
    cur.execute (comando_sql)
    arq = open("relatorio_diario.txt", "w")
    rows = cur.fetchall()
    for row in rows:
        numos = row[0]
        setor = row[1]
        solicitante = row[2]
        equip_nome = row[3]
        solicitante = solicitante if solicitante is not None else "Nao Informado"
        equip_nome = equip_nome if equip_nome is not None else "Nao Informado"
        arq.write('_OS: {} - Setor: {} - Solicitante: {}\n - Equipamento: {}\n Resolucao: '.format(numos, setor, solicitante, equip_nome))
        arq.write("\n")
        arq.write("------------------------------------------------------")
        arq.write("\n")
        arq.close()

import psycopg2
myConnection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database)
doQuery( myConnection )
myConnection.close()
    
asked by anonymous 06.07.2017 / 23:58

1 answer

0

To make sure you're using the correct encoding, try the command:

print (myConnection.encoding)

The output should be:

UTF8

If you do not try to configure with the command:

myConnection.set_client_encoding('UTF8')

Or:

myConnection.set_client_encoding('UNICODE')

If this does not resolve and you have access to the Postgres configuration file, postgresql.conf check the lines for the lc_ settings, a block like this:

# These settings are initialized by initdb, but they can be changed.
lc_messages = 'pt_BR.UTF-8'         # locale for system error message
# strings
lc_monetary = 'pt_BR.UTF-8'         # locale for monetary formatting
lc_numeric = 'pt_BR.UTF-8'          # locale for number formatting
lc_time = 'pt_BR.UTF-8'             # locale for time formatting
    
07.07.2017 / 01:18