python 连接pgsql
时间: 2025-02-19 09:32:16 浏览: 44
### 使用 Python 连接到 PostgreSQL 数据库
为了实现 Python 和 PostgreSQL 的连接,通常会使用 `psycopg2` 或者更现代的 `sqlalchemy` 库来建立这种链接。下面展示的是通过 `psycopg2` 来完成这一操作的方式。
#### 安装 psycopg2
首先需要安装 `psycopg2`,可以通过 pip 工具轻松做到这一点:
```bash
pip install psycopg2-binary
```
#### 创建连接函数
创建一个用于获取所有学生的函数作为例子,这里修改为连接至 PostgreSQL 并执行查询命令[^1]。
```python
import psycopg2
from psycopg2 import sql, extras
def get_all_students():
try:
# 建立与 PostgreSQL 数据库之间的连接
connection = psycopg2.connect(
dbname="your_dbname", # 替换为实际数据库名称
user="your_username", # 用户名
password="your_password", # 密码
host="localhost", # 主机地址,默认本地
port="5432" # 默认端口
)
with connection.cursor(cursor_factory=extras.DictCursor) as cursor:
query = "SELECT * FROM Students;"
cursor.execute(query)
students = cursor.fetchall()
for student in students:
print(student)
except (Exception, psycopg2.DatabaseError) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
if(connection):
cursor.close()
connection.close()
get_all_students()
```
此代码片段展示了如何安全地打开和关闭数据库连接,并处理可能发生的异常情况。同时利用了上下文管理器(`with`)自动管理游标的生命周期。
阅读全文
相关推荐


















