1. 准备工作
在开始之前,你需要:
- 安装mysql服务器
- 安装python的mysql连接库
推荐使用mysql-connector-python或pymysql库:
pip install mysql-connector-python # 或 pip install pymysql
2. 连接mysql数据库
使用mysql-connector
import mysql.connector # 创建连接 conn = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) # 创建游标 cursor = conn.cursor() # 执行sql查询 cursor.execute("select * from your_table") # 获取结果 results = cursor.fetchall() for row in results: print(row) # 关闭连接 cursor.close() conn.close()
使用pymysql
import pymysql # 创建连接 conn = pymysql.connect( host='localhost', user='your_username', password='your_password', db='your_database', charset='utf8mb4', cursorclass=pymysql.cursors.dictcursor ) # 使用上下文管理器自动管理连接 with conn: with conn.cursor() as cursor: # 执行sql查询 sql = "select * from your_table" cursor.execute(sql) # 获取结果 results = cursor.fetchall() for row in results: print(row)
3. 基本crud操作
创建表
cursor.execute(""" create table if not exists users ( id int auto_increment primary key, name varchar(255) not null, email varchar(255) not null unique, created_at timestamp default current_timestamp ) """)
插入数据
# 单条插入 sql = "insert into users (name, email) values (%s, %s)" val = ("john doe", "john@example.com") cursor.execute(sql, val) # 多条插入 sql = "insert into users (name, email) values (%s, %s)" val = [ ("jane smith", "jane@example.com"), ("bob johnson", "bob@example.com") ] cursor.executemany(sql, val) # 提交事务 conn.commit()
查询数据
# 查询所有记录 cursor.execute("select * from users") rows = cursor.fetchall() # 查询单条记录 cursor.execute("select * from users where id = %s", (1,)) row = cursor.fetchone() # 带条件的查询 cursor.execute("select name, email from users where name like %s", ("%john%",)) rows = cursor.fetchall()
更新数据
sql = "update users set name = %s where id = %s" val = ("john smith", 1) cursor.execute(sql, val) conn.commit()
删除数据
sql = "delete from users where id = %s" val = (1,) cursor.execute(sql, val) conn.commit()
4. 高级操作
事务处理
try: # 开始事务 conn.start_transaction() # 执行多个sql操作 cursor.execute(sql1, val1) cursor.execute(sql2, val2) # 提交事务 conn.commit() except exception as e: # 发生错误时回滚 conn.rollback() print(f"transaction failed: {e}")
使用orm框架 - sqlalchemy
from sqlalchemy import create_engine, column, integer, string from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 创建引擎 engine = create_engine('mysql+pymysql://user:password@localhost/dbname') # 声明基类 base = declarative_base() # 定义模型 class user(base): __tablename__ = 'users' id = column(integer, primary_key=true) name = column(string(255)) email = column(string(255), unique=true) # 创建表 base.metadata.create_all(engine) # 创建会话 session = sessionmaker(bind=engine) session = session() # 添加新用户 new_user = user(name='alice', email='alice@example.com') session.add(new_user) session.commit() # 查询用户 users = session.query(user).filter_by(name='alice').all() for user in users: print(user.name, user.email)
5. 最佳实践
使用参数化查询:防止sql注入攻击
使用上下文管理器:确保连接和游标正确关闭
处理异常:捕获并处理数据库操作中的异常
连接池:在高并发应用中使用连接池
索引优化:为常用查询字段添加索引
6. 常见错误处理
try: conn = mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute("select * from non_existent_table") except mysql.connector.error as err: print(f"error: {err}") finally: if 'conn' in locals() and conn.is_connected(): cursor.close() conn.close()
连接池
1.连接池的作用
数据库连接池是一种预先创建并管理数据库连接的技术,主要解决频繁创建/销毁连接的性能损耗问题。其核心思想是连接复用,应用程序从池中获取连接,使用后归还而非直接关闭。
2.优势与劣势
优势:
性能提升:减少连接创建/销毁的tcp三次握手和认证开销,降低延迟
资源控制:通过max_connections限制最大连接数,防止数据库过载
响应加速:初始化时预建连接,业务请求可直接使用
泄漏防护:超时回收机制避免连接长期占用
劣势:
需要合理配置参数(如最大/最小连接数)
连接状态维护增加复杂度
不适用于超短生命周期应用
3.部署与使用
1. 常用库及安装
# sqlalchemy(支持多种数据库) pip install sqlalchemy # dbutils(通用连接池) pip install dbutils # psycopg2(postgresql专用) pip install psycopg2-binary
2. 基础使用示例
sqlalchemy连接池配置:
from sqlalchemy import create_engine # 带连接池的配置(连接池大小5-10) engine = create_engine( "mysql+pymysql://user:pass@host/db", pool_size=5, max_overflow=5, pool_recycle=3600 )
dbutils连接池示例:
from dbutils.pooled_db import pooleddb import pymysql pool = pooleddb( creator=pymysql, maxconnections=10, host='localhost', user='root', database='test' ) conn = pool.connection() # 获取连接
3. 生产环境建议
根据qps设置pool_size(建议=平均并发量×1.2)
启用pool_pre_ping自动检测失效连接
使用with语句确保连接归还
监控连接池使用率(如sqlalchemy的pool.status())
4.性能优化技巧
不同业务使用独立连接池隔离资源
动态调整连接数(如sqlalchemy的pool_events)
配合连接池使用orm的session缓存机制
事务管理
事务核心概念
acid特性
- 原子性(atomicity):事务是不可分割的工作单元
- 一致性(consistency):事务前后数据库状态保持一致
- 隔离性(isolation):并发事务互不干扰
- 持久性(durability):事务提交后结果永久生效
隔离级别
- read_uncommitted(可能读取未提交数据)
- read_committed(避免脏读)
- repeatable_read(避免不可重复读)
- serializable(完全串行化)
四大隔离级别对比
隔离级别 | 脏读 | 不可重复读 | 幻读 | 锁机制特点 |
---|---|---|---|---|
read uncommitted | ✓ | ✓ | ✓ | 无读锁,仅写锁冲突 |
read committed | ✗ | ✓ | ✓ | 读后立即释放共享锁 |
repeatable read | ✗ | ✗ | ✓* | 持有读锁至事务结束 |
serializable | ✗ | ✗ | ✗ | 范围锁防止幻读 |
*注:mysql的innodb通过mvcc机制在repeatable read下可避免幻读
典型问题场景
脏读:事务a读取事务b未提交的修改,b回滚导致a获得无效数据
不可重复读:事务a两次读取同记录,因事务b提交修改导致结果不一致
幻读:事务a按条件查询,事务b新增符合条件记录导致a两次结果集不同
选型建议
实时分析系统:read uncommitted(容忍脏读换取性能)
支付系统:repeatable read(保证金额一致性)
票务系统:serializable(杜绝超卖风险)
常规oltp:read committed(平衡性能与一致性)
python配置示例
# postgresql设置隔离级别 import psycopg2 conn = psycopg2.connect(dsn) conn.set_isolation_level( psycopg2.extensions.isolation_level_repeatable_read )
不同数据库对隔离级别的实现存在差异,如oracle默认read committed而mysql默认repeatable read38,实际开发需结合具体数据库特性调整
到此这篇关于python远程控制mysql的完整指南的文章就介绍到这了,更多相关python远程控制mysql内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论