文章目录
- import psycopg2 # 建立连接 conn = psycopg2.connect( dbname=”your_database”, user=”your_username”, password=”your_password”, host=”your_host”, port=”your_port” ) # 创建游标对象 cur = conn.cursor()
- # 执行简单查询 cur.execute(“SELECT * FROM your_table LIMIT 5;”) # 获取结果 rows = cur.fetchall() for row in rows: print(row)
- # 使用参数化查询 user_id = 5 cur.execute(“SELECT * FROM users WHERE id = %s;”, (user_id,)) user = cur.fetchone() print(user)
- # 插入单条数据 cur.execute( “INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id;”, (‘John Doe’, ‘john@example.com’) ) user_id = cur.fetchone()[0] conn.commit() # 必须提交事务 print(f”插入的用户ID: {user_id}”) # 批量插入 users_data = [ (‘Alice’, ‘alice@example.com’), (‘Bob’, ‘bob@example.com’), (‘Charlie’, ‘charlie@example.com’) ] cur.executemany( “INSERT INTO users (name, email) VALUES (%s, %s);”, users_data ) conn.commit()
- cur.execute( “UPDATE users SET email = %s WHERE id = %s;”, (‘new_email@example.com’, 1) ) conn.commit()
- cur.execute( “DELETE FROM users WHERE id = %s;”, (5,) ) conn.commit()
目录
- 安装psycopg2
- 基本连接与操作
- 1. 建立数据库连接
- 2. 执行SQL查询
- 3. 执行参数化查询(防止SQL注入)
- 4. 插入数据
- 5. 更新数据
- 6. 删除数据
- 使用上下文管理器(推荐)
- 使用连接池(适用于Web应用)
- 使用SQLAlchemy(ORM方式)
- 注意事项
在Python中连接PostgreSQL数据库,最常用的库是psycopg2。以下是详细的使用指南:
首先需要安装psycopg2库:
pip install psycopg2 # 或者使用二进制版本(安装更快) pip install psycopg2-binary
import psycopg2
# 建立连接
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# 创建游标对象
cur = conn.cursor()
# 执行简单查询
cur.execute("SELECT * FROM your_table LIMIT 5;")
# 获取结果
rows = cur.fetchall()
for row in rows:
print(row)
# 使用参数化查询
user_id = 5
cur.execute("SELECT * FROM users WHERE id = %s;", (user_id,))
user = cur.fetchone()
print(user)
# 插入单条数据
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id;",
('John Doe', 'john@example.com')
)
user_id = cur.fetchone()[0]
conn.commit() # 必须提交事务
print(f"插入的用户ID: {user_id}")
# 批量插入
users_data = [
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com'),
('Charlie', 'charlie@example.com')
]
cur.executemany(
"INSERT INTO users (name, email) VALUES (%s, %s);",
users_data
)
conn.commit()
cur.execute(
"UPDATE users SET email = %s WHERE id = %s;",
('new_email@example.com', 1)
)
conn.commit()
cur.execute(
"DELETE FROM users WHERE id = %s;",
(5,)
)
conn.commit()
# 使用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应用等需要频繁连接数据库的场景,可以使用连接池:
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)
如果你更喜欢使用ORM,可以安装SQLAlchemy:
pip install sqlalchemy psycopg2-binary
然后使用:
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数据库连接的详细使用指南的详细内容,更多关于Python PostgreSQL数据库连接的资料请关注风君子博客其它相关文章!
您可能感兴趣的文章:
- 使用python进行PostgreSQL数据库连接全过程
- Python连接PostgreSQL数据库并查询数据的详细指南
- Python如何管理多个PostgreSQL数据库的连接
- Python连接和操作PostgreSQL数据库的流程步骤
- Python访问PostgreSQL数据库详细操作
- Python连接到PostgreSQL数据库的方法详解
- Python操作PostgreSQL数据库的基本方法(增删改查)