1

I am using a postgres database and connecting it using psycopg2 connector. Here is my code below

import psycopg2

conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=port)
cur = conn.cursor()

try:
    cur.execute(sql_query)
    result = cur.fetchall()
except Exception as e:
    print("Could not get results")
    conn.rollback()

Now the problem is I receive this error when I try to retrieve data from db

Traceback (most recent call last):
  File "/home/ec2-user/connection/dbaccess.py", line 119, in get_results_of_query
    result = cur.fetchall()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 20: ordinal not in range(128)

Now on looking up online, I found some posts where they asked to use set_client_encoding('UTF8')

So this is what I did

conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=port)
cur = conn.cursor()
conn.set_client_encoding('UTF8')

And then I tried to run it again. But I still receive the same error like before. What am I doing wrong?

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70
  • 1
    What is the value of `sql_query` and what data is there in the data base? – zvone Dec 27 '19 at 08:13
  • Does this answer your question? [How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"](https://stackoverflow.com/questions/21129020/how-to-fix-unicodedecodeerror-ascii-codec-cant-decode-byte) – mrEvgenX Dec 27 '19 at 08:39

0 Answers0