python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python PostgreSQL数据库连接

Python进行PostgreSQL数据库连接的详细使用指南

作者:懒大王爱吃狼

在Python中连接PostgreSQL数据库,最常用的库是psycopg2,本文为大家详细介绍了Python使用psycopg2库操作PostgreSQL的详细步骤,需要的可以了解下

在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数据库连接的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文