为什么我会遇到这样的问题?你是怎么解决的?我正在尝试连接到 postgresql
import psycopg2
conn = psycopg2.connect(database="test", user="postgres", password="260508", host="localhost", port="5432")
print("Database Connected....")
结果我有错误。
Traceback (most recent call last):
File "C:\Users\gamer\Desktop\PyCharm Workspace\PyCharm Workspace\SQL Test\SQL Test\main.py", line 3, in <module>
conn = psycopg2.connect(database="test", user="postgres", password="260508", host="localhost", port="5432")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\gamer\Desktop\PyCharm Workspace\PyCharm Workspace\SQL Test\SQL Test\.venv\Lib\site-packages\psycopg2\__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
我试图像那样解码和编码
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....")
您使用的编码方法是否正确您可以通过运行来检查:
print(conn.encoding)
,如果需要,可以通过
conn.set_client_encoding('UNICODE')
或 conn.set_client_encoding('UTF8')
设置正确的编码