执行如下命令安装
pip3 install psycopg2
python代码
'''
Author: tkhywang 2810248865@qq.com
Date: 2023-08-21 11:42:17
LastEditors: tkhywang 2810248865@qq.com
LastEditTime: 2023-08-21 11:51:56
FilePath: \PythonProject02\PostgreSQL 数据库.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import psycopg2
# 连接数据库
#conn = psycopg2.connect(database="database_name", user="username", password="password", host="localhost", port="5432")
conn = psycopg2.connect(database="sales_db", user="sales_user", password="123456@abc.COM", host="192.168.56.15", port="5432")
# 执行查询
cur = conn.cursor()
cur.execute("SELECT id, tname FROM public.test1;")
# 获取结果
rows = cur.fetchall()
for row in rows:
print(row)
# 关闭连接
cur.close()
conn.close()
连接成功输入