一、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数据库自动化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论