Python 数据库操作:连接 MySQL 和 PostgreSQL 的方法详解
在 Python 中连接和操作数据库,可以使用以下方法和库来连接常见的关系型数据库如 MySQL 和 PostgreSQL:
1. 连接 MySQL
安装依赖库:
bash
pip install pymysql
示例代码:
python
import pymysql
# 连接 MySQL 数据库
connection = pymysql.connect(
host='localhost', # 数据库地址
user='root', # 用户名
password='your_password',# 密码
database='your_database' # 数据库名
)
try:
with connection.cursor() as cursor:
# 查询数据
cursor.execute("SELECT * FROM your_table")
results = cursor.fetchall()
for row in results:
print(row)
finally:
connection.close() # 关闭连接
2. 连接 PostgreSQL
安装依赖库:
bash
pip install psycopg2
示例代码:
python
import psycopg2
# 连接 PostgreSQL 数据库
connection = psycopg2.connect(
host="localhost",
database="your_database",
user="your_user",
password="your_password"
)
try:
with connection.cursor() as cursor:
# 查询数据
cursor.execute("SELECT * FROM your_table")
results = cursor.fetchall()
for row in results:
print(row)
finally:
connection.close() # 关闭连接
3. SQLAlchemy 通用解决方案
如果你希望使用 ORM(对象关系映射)来更方便地管理数据库,可以使用 SQLAlchemy。
安装依赖库:
bash
pip install sqlalchemy
示例代码:
python
from sqlalchemy import create_engine, Table, MetaData
# 创建数据库引擎(以 MySQL 为例)
engine = create_engine("mysql+pymysql://root:your_password@localhost/your_database")
# 测试连接
with engine.connect() as connection:
result = connection.execute("SELECT * FROM your_table")
for row in result:
print(row)
# 结合 ORM
from sqlalchemy.orm import declarative_base, sessionmaker
Base = declarative_base()
# 定义一个表
class YourTable(Base):
__tablename__ = 'your_table'
id = Column(Integer, primary_key=True)
name = Column(String)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 查询数据
for item in session.query(YourTable).all():
print(item.name)
4. 数据库连接池:使用 mysql-connector或 psycopg2连接池
如果你的程序需要频繁连接数据库,可以使用连接池来提高效率。
MySQL连接池示例:
python
from mysql.connector import pooling
# 创建连接池
db_pool = pooling.MySQLConnectionPool(
pool_name="mypool",
pool_size=5,
host="localhost",
user="root",
password="your_password",
database="your_database"
)
# 获取连接
connection = db_pool.get_connection()
PostgreSQL连接池示例:
python
from psycopg2 import pool
# 创建连接池
db_pool = pool.SimpleConnectionPool(
1, 10, # 最小和最大连接数
host="localhost",
database="your_database",
user="your_user",
password="your_password"
)
# 获取连接
connection = db_pool.getconn()
小贴士
- 配置文件管理: 将数据库配置存储在 .env 文件中,使用 dotenv 加载配置。
- 安全性: 避免直接在代码中写明密码,优先使用环境变量。
- 防止 SQL 注入: 使用参数化查询,避免直接拼接 SQL 字符串。