python连接PostgreSQL 数据库

python连接PostgreSQL 数据库_第1张图片

 

 

执行如下命令安装

pip3 install psycopg2

 python代码

'''
Author: tkhywang [email protected]
Date: 2023-08-21 11:42:17
LastEditors: tkhywang [email protected]
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="[email protected]", 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()

 连接成功输入

python连接PostgreSQL 数据库_第2张图片

 

你可能感兴趣的:(数据库,python,postgresql)