Python数据库连接全解析:5大方案实战对比

在本文中,我们将通过实际示例,深入探讨Python中5种主流的数据库连接方案。这些例子将帮助您更好地理解每种方法的特点和适用场景。
目录
不同方案说明
1. DB-API:以sqlite3为例
2. SQLAlchemy:ORM示例
3. psycopg2:PostgreSQL连接
4. pymysql:MySQL连接
5. sqlite3:Python标准库
结语
实战对比
测试环境
1. 插入性能测试
2. 查询性能测试
3. 连接开销
4. 代码复杂度比较
5. 特性对比
结论
选择建议
不同方案说明
1. DB-API:以sqlite3为例
DB-API是Python标准数据库API,几乎所有Python数据库模块都遵循这个接口。
import sqlite3
# 连接到数据库(如果不存在则创建)
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
# 插入数据
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)",
('John Doe', 'john@example.com'))
# 查询数据
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
# 提交更改并关闭连接
conn.commit()
conn.close()
2. SQLAlchemy:ORM示例
SQLAlchemy是一个强大的ORM工具,支持多种数据库。
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
# 创建引擎和会话
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine