Python数据库自动化完整指南
作者:老胖闲聊
本指南详细讲解如何使用Python操作MySQL、Oracle和Microsoft SQL Server数据库,涵盖常用库、基础操作、高级功能及完整代码示例,需要的朋友可以参考下
一、MySQL 操作详解
1. 常用库
- mysql-connector-python(官方驱动)
安装:pip install mysql-connector-python
- PyMySQL(纯 Python 实现)
安装:pip install pymysql
2. 基础操作
连接数据库
import mysql.connector config = { 'user': 'root', 'password': '123456', 'host': 'localhost', 'database': 'test_db' } conn = mysql.connector.connect(**config) cursor = conn.cursor()
执行 SQL
# 创建表 cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255) ) """) # 插入数据 cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", ('Alice', 'alice@example.com')) conn.commit()
3. 高级功能
事务管理
try: cursor.execute("INSERT INTO users (name) VALUES ('Bob')") cursor.execute("UPDATE users SET email='error' WHERE id=999") # 模拟错误 conn.commit() except mysql.connector.Error as e: conn.rollback()
二、Oracle 操作详解
1. 常用库
- cx_Oracle(官方推荐)
安装:pip install cx_Oracle
依赖:需安装 Oracle Instant Client
2. 基础操作
连接数据库
import cx_Oracle dsn = cx_Oracle.makedsn("localhost", 1521, service_name="ORCLCDB") conn = cx_Oracle.connect(user="scott", password="tiger", dsn=dsn) cursor = conn.cursor()
执行 SQL
# 使用序列插入数据 cursor.execute("CREATE SEQUENCE user_seq START WITH 1 INCREMENT BY 1") cursor.execute(""" INSERT INTO users (id, name) VALUES (user_seq.NEXTVAL, :name)""", name="Charlie") conn.commit()
3. 高级功能
调用存储过程
p_name = cursor.var(str) cursor.callproc("get_user", [1, p_name]) print(p_name.getvalue()) # 输出结果
三、Microsoft SQL Server 操作详解
1. 常用库
- pyodbc(推荐)
安装:pip install pyodbc
依赖:需安装 ODBC Driver - pymssql(轻量级)
安装:pip install pymssql
2. 基础操作
连接数据库
import pyodbc conn = pyodbc.connect( Driver='{ODBC Driver 17 for SQL Server}', Server='localhost', Database='test_db', UID='sa', PWD='password' ) cursor = conn.cursor()
执行 SQL
# 分页查询(OFFSET FETCH) cursor.execute(""" SELECT * FROM users ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY """) print(cursor.fetchall())
3. 高级功能
批量插入
data = [('David', 'david@example.com'), ('Eva', 'eva@example.com')] cursor.executemany("INSERT INTO users (name, email) VALUES (?, ?)", data) conn.commit()
四、通用注意事项
1. 安全与性能
- 参数化查询:始终使用占位符(
%s
、?
、:name
)避免 SQL 注入。 - 连接管理:使用
with
上下文管理器或封装类确保连接关闭。
# 示例:MySQL 上下文管理器 with mysql.connector.connect(**config) as conn: with conn.cursor() as cursor: cursor.execute("SELECT 1")
2. 异常处理
try: conn = cx_Oracle.connect("invalid_connection") except cx_Oracle.DatabaseError as e: error = e.args[0] print(f"Code: {error.code}, Message: {error.message}") finally: if conn: conn.close()
3. 自动化封装类
class DatabaseAutomator: """通用数据库操作封装""" def __init__(self, db_type, **config): self.db_type = db_type self.config = config self.conn = None def __enter__(self): if self.db_type == "mysql": self.conn = mysql.connector.connect(**self.config) elif self.db_type == "oracle": dsn = cx_Oracle.makedsn(**self.config) self.conn = cx_Oracle.connect(user=self.config['user'], password=self.config['password'], dsn=dsn) # 其他数据库类似 return self.conn.cursor() def __exit__(self, exc_type, exc_val, exc_tb): if self.conn: if exc_type: self.conn.rollback() else: self.conn.commit() self.conn.close() # 使用示例 with DatabaseAutomator("mysql", user="root", password="123456", host="localhost", database="test_db") as cursor: cursor.execute("SELECT * FROM users")
4. ORM 集成
- SQLAlchemy 统一操作不同数据库:
from sqlalchemy import create_engine # MySQL engine = create_engine("mysql+pymysql://user:password@localhost/db") # Oracle engine = create_engine("oracle+cx_oracle://user:password@localhost:1521/ORCLCDB") # SQL Server engine = create_engine("mssql+pyodbc://user:password@localhost/db?driver=ODBC+Driver+17+for+SQL+Server") with engine.connect() as conn: result = conn.execute("SELECT * FROM users") print(result.fetchall())
通过本文档,可快速掌握 Python 操作三大主流数据库的核心方法。根据场景选择合适的库和工具,结合 ORM 框架可进一步提升开发效率。
到此这篇关于Python数据库自动化完整指南的文章就介绍到这了,更多相关Python数据库自动化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!