Psycopg2 PostgreSQL驱动:Python数据库连接指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Psycopg2:Python操作PostgreSQL完全指南

简介

PostgreSQL 是一款功能强大的开源关系型数据库管理系统,以其可靠性、可扩展性以及对复杂数据类型的支持而闻名。在Python中操作PostgreSQL,最流行且最可靠的工具是 Psycopg2——官方同步驱动程序,它提供了稳定高效的数据库连接方案,支持SQL查询执行、事务管理以及与Web框架的无缝集成。

Psycopg2 凭借其成熟度、功能完整性和活跃的社区支持,已成为Python项目中使用PostgreSQL的事实标准。

什么是Psycopg2

Psycopg2 是一个用C语言编写的Python PostgreSQL适配器,底层基于 libpq(PostgreSQL官方客户端库)。该库完全符合 DB-API 2.0 规范,并提供了许多PostgreSQL特有的高级功能。

Psycopg2 核心特性:

  • 高性能:基于C语言实现,与libpq高效交互
  • 安全可靠:通过参数化查询内置SQL注入防护
  • 事务支持:完全控制事务,支持自动管理
  • 数据类型兼容:自动在PostgreSQL与Python类型间转换
  • 扩展支持:处理JSON、UUID、数组、hstore等PostgreSQL特殊类型
  • 线程安全:可在多线程应用中安全使用

安装与配置

安装库

pip install psycopg2-binary

生产环境建议安装完整版本:

pip install psycopg2

系统依赖

安装前请确保系统已安装必要的依赖:

Ubuntu/Debian:

sudo apt-get install libpq-dev python3-dev

CentOS/RHEL:

sudo yum install postgresql-devel python3-devel

macOS:

brew install postgresql

连接数据库

基本连接

import psycopg2

# 连接PostgreSQL
conn = psycopg2.connect(
    dbname="mydb",
    user="postgres", 
    password="password",
    host="localhost",
    port="5432"
)

# 创建游标
cur = conn.cursor()

使用连接字符串

conn = psycopg2.connect("postgresql://user:password@localhost:5432/dbname")

带额外参数的连接

conn = psycopg2.connect(
    dbname="mydb",
    user="postgres",
    password="password",
    host="localhost",
    port="5432",
    sslmode="require",
    connect_timeout=10,
    application_name="my_app"
)

使用上下文管理器

import psycopg2
from contextlib import contextmanager

@contextmanager
def get_db_connection():
    conn = psycopg2.connect(
        dbname="mydb",
        user="postgres",
        password="password",
        host="localhost"
    )
    try:
        yield conn
    finally:
        conn.close()

# 使用示例
with get_db_connection() as conn:
    with conn.cursor() as cur:
        cur.execute("SELECT * FROM users")
        results = cur.fetchall()

推荐