12

I use Python to connect to my postgresql data base like this:

conn=psycopg2.connect(database="fedour", user="fedpur", password="***", host="127.0.0.1", port="5432")

No problem for that.

But when I make a query and I want to print the cursor I have something like this:

"Fran\xc3\xa7ois" instead of "François" and it cause problem when I want to create a XML document with this. I thkink is come from my encodage, but I found any solution. I try to encode('utf-8') but doesn't work.

I have also seen something like this, but its only for mySQL

MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')

Can you help me ? Thanks

Fedour
  • 367
  • 1
  • 3
  • 18

2 Answers2

28

Make sure you're using the right encodind by running: print conn.encoding, and if you need, you can set the right encoding by conn.set_client_encoding('UNICODE'), or conn.set_client_encoding('UTF8').

lch
  • 2,028
  • 2
  • 25
  • 46
  • 1
    You beautiful, beautiful person - this is the perfect fix. Trying to read data from Postgres - and for some reason the library seems to default to SQLASCII. But fixed now due to your answer. – Vidar Jan 04 '23 at 16:06
0

Does the value get inserted correctly when query is executed via command prompt?

If yes, then the problem is with your cursor execution.Try cur.execute(u"querystring");(The u indicates utf encoding)

If no, then you need to set the encoding type of postgres to consider utf-8. You can refer character encoding in Postgres to see how to set default character encoding for a database, and on-the-fly conversion from one encoding to another.

Brindha
  • 349
  • 1
  • 5
  • 16