在python中连接postgresql数据库,最常用的库是psycopg2。以下是详细的使用指南:
安装psycopg2
首先需要安装psycopg2库:
pip install psycopg2 # 或者使用二进制版本(安装更快) pip install psycopg2-binary
基本连接与操作
1. 建立数据库连接
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查询
# 执行简单查询 cur.execute("select * from your_table limit 5;") # 获取结果 rows = cur.fetchall() for row in rows: print(row)
3. 执行参数化查询(防止sql注入)
# 使用参数化查询 user_id = 5 cur.execute("select * from users where id = %s;", (user_id,)) user = cur.fetchone() print(user)
4. 插入数据
# 插入单条数据 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()
5. 更新数据
cur.execute( "update users set email = %s where id = %s;", ('new_email@example.com', 1) ) conn.commit()
6. 删除数据
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应用)
对于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)
使用sqlalchemy(orm方式)
如果你更喜欢使用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数据库连接的资料请关注代码网其它相关文章!
发表评论