2
I have an error when running the command below, generates the text file correctly when importing texts from the database without accentuation, but when there is some accentuation appears the error:
File "C:/Users/ti/Desktop/reportario.py", line 17, in doQuery Rows = cur.fetchall() Unicodedecodeerror: 'ascii' codec can’t 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()
It was a mistake to paste here.
– Yuri Florencio
I don’t have any experience with psycopg2, but I suspect some additional command is needed if you want to handle Unicode data. What is your database encoding? You may need to use
myConnection.set_client_encoding("...")
before callingdoQuery
, passing the same encoding of your BD as argument. P.S. Maybe I’m wrong, the treatment of Unicode in python 2 and python 3 is different. I suggest you take a look in this section of the documentation, I can’t tell you exactly what to do, but maybe I can give you an idea.– mgibsonbr
Could you tell me which other one I can use besides psycopg2? My database is in postgresql
– Yuri Florencio
If you’re going to connect with Postgres, psycopg2 is really the best solution, I don’t know any other... Just in case you figure out how to use it properly.
– mgibsonbr