skip to Main Content

Why I have problem like that? How did you solve that? I am trying to connect to postgresql

import psycopg2

conn = psycopg2.connect(database="test", user="postgres", password="260508", host="localhost", port="5432")
print("Database Connected....")

in result i have error.

Traceback (most recent call last):
  File "C:UsersgamerDesktopPyCharm WorkspacePyCharm WorkspaceSQL TestSQL Testmain.py", line 3, in <module>
    conn = psycopg2.connect(database="test", user="postgres", password="260508", host="localhost", port="5432")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersgamerDesktopPyCharm WorkspacePyCharm WorkspaceSQL TestSQL Test.venvLibsite-packagespsycopg2__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd4 in position 61: invalid continuation byte

I was trying to decode and encode like that

import psycopg2
import base64

password = "260508".encode('utf-8')  # Encode directly to UTF-8
encoded_password = base64.b64encode(password).decode('utf-8') 

conn = psycopg2.connect(database="test", user="postgres", password=encoded_password, host="localhost", port="5432")
print("Database Connected....")

2

Answers


  1. Chosen as BEST ANSWER

    So the problem was in the name of database :) Idk why there was UnicodeDecodeError, if i had problem with the name of database. Thanks everybody for help :) Everybody who has the same problem, be sure that you have right database name


  2. Are You using the correct Encoding method You can check that 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')

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search