使用Python连接PostgreSQL数据库
在Python中连接PostgreSQL数据库,最常用的库是psycopg2
。以下是详细的使用指南:
安装psycopg2
首先需要安装psycopg2库:
bash
pip install psycopg2
# 或者使用二进制版本(安装更快)
pip install psycopg2-binary
基本连接与操作
1. 建立数据库连接
python
import psycopg2
# 建立连接
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# 创建游标对象
cur = conn.cursor()
2. 执行SQL查询
python
# 执行简单查询
cur.execute("SELECT * FROM your_table LIMIT 5;")
# 获取结果
rows = cur.fetchall()
for row in rows:
print(row)
3. 执行参数化查询(防止SQL注入)
python
# 使用参数化查询
user_id = 5
cur.execute("SELECT * FROM users WHERE id = %s;", (user_id,))
user = cur.fetchone()
print(user)
4. 插入数据
python
# 插入单条数据
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id;",
('John Doe', '[email protected]')
)
user_id = cur.fetchone()[0]
conn.commit() # 必须提交事务
print(f"插入的用户ID: {user_id}")
# 批量插入
users_data = [
('Alice', '[email protected]'),
('Bob', '[email protected]'),
('Charlie', '[email protected]')
]
cur.executemany(
"INSERT INTO users (name, email) VALUES (%s, %s);",
users_data
)
conn.commit()
5. 更新数据
python
cur.execute(
"UPDATE users SET email = %s WHERE id = %s;",
('[email protected]', 1)
)
conn.commit()
6. 删除数据
python
cur.execute(
"DELETE FROM users WHERE id = %s;",
(5,)
)
conn.commit()
使用上下文管理器(推荐)
python
# 使用with语句自动管理连接
with psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host"
) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM users;")
for row in cur:
print(row)
# 不需要显式调用commit()或close(),with语句会自动处理
使用连接池(适用于Web应用)
对于Web应用等需要频繁连接数据库的场景,可以使用连接池:
python
from psycopg2 import pool
# 创建连接池
connection_pool = pool.SimpleConnectionPool(
minconn=1,
maxconn=10,
dbname="your_database",
user="your_username",
password="your_password",
host="your_host"
)
# 从连接池获取连接
conn = connection_pool.getconn()
cur = conn.cursor()
cur.execute("SELECT * FROM users;")
# ... 执行操作 ...
# 将连接返回给连接池
connection_pool.putconn(conn)
使用SQLAlchemy(ORM方式)
如果你更喜欢使用ORM,可以安装SQLAlchemy:
bash
pip install sqlalchemy psycopg2-binary
然后使用:
python
from sqlalchemy import create_engine, text
# 创建引擎
engine = create_engine('postgresql://user:password@localhost:5432/dbname')
# 执行查询
with engine.connect() as connection:
result = connection.execute(text("SELECT * FROM users;"))
for row in result:
print(row)
注意事项
- 始终记得提交事务(
conn.commit()
)或回滚(conn.rollback()
) - 使用参数化查询防止SQL注入
- 操作完成后关闭游标和连接
- 对于生产环境,考虑使用连接池
- 将数据库凭据存储在环境变量或配置文件中,不要硬编码在代码里
以上是Python连接和操作PostgreSQL数据库的基本方法。根据你的具体需求,可以选择最适合的方式。