python 连接 postgres
时间: 2023-07-11 11:08:53 浏览: 64
要在 Python 中连接 PostgreSQL 数据库,需要使用 Python 的 psycopg2 模块。以下是连接 PostgreSQL 数据库的基本步骤:
1. 安装 psycopg2 模块
使用以下命令安装 psycopg2 模块:
```
pip install psycopg2
```
2. 导入 psycopg2 模块
在 Python 代码中导入 psycopg2 模块:
```
import psycopg2
```
3. 连接 PostgreSQL 数据库
使用以下代码连接 PostgreSQL 数据库:
```
conn = psycopg2.connect(
host="your_host",
database="your_database",
user="your_username",
password="your_password"
)
```
其中,your_host 是 PostgreSQL 服务器的主机名或 IP 地址,your_database 是要连接的数据库名称,your_username 和 your_password 分别是连接 PostgreSQL 数据库所需的用户名和密码。
4. 执行 SQL 查询
使用以下代码执行 SQL 查询:
```
cur = conn.cursor()
cur.execute("SELECT * FROM your_table")
rows = cur.fetchall()
for row in rows:
print(row)
```
其中,your_table 是要查询的表的名称。
5. 关闭数据库连接
使用以下代码关闭数据库连接:
```
conn.close()
```
完整的示例代码如下所示:
```
import psycopg2
conn = psycopg2.connect(
host="your_host",
database="your_database",
user="your_username",
password="your_password"
)
cur = conn.cursor()
cur.execute("SELECT * FROM your_table")
rows = cur.fetchall()
for row in rows:
print(row)
conn.close()
```
请注意,上述示例代码中的参数值应根据您的实际情况进行更改。