mysql查看查询语句性能explain
2021/9/24 19:14:04
本文主要是介绍mysql查看查询语句性能explain,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
https://bbs.huaweicloud.com/blogs/177202
https://www.cnblogs.com/yycc/p/7338894.html
先用explain查看性能,如果性能达标可以执行,如果不达标需要添加索引查询
from sqlalchemy import create_engine class ConnectMysql: """操作Mysql""" instance = None def __new__(cls, *args, **kwargs): if not cls.instance: cls.instance = object.__new__(cls) return cls.instance else: return cls.instance def __init__(self, db_url, db_name): self.engine = create_engine(db_url + db_name) self.conn = self.engine.connect() def execute(self, sql): """执行sql语句,仅限创建/删除索引""" try: assert ('alter' in sql or 'ALTER' in sql or 'drop' in sql or 'DROP' in sql), '非创建/删除索引语句,查询请用fetch_one' self.conn.execute(sql) except Exception as e: log.error("非创建/删除索引语句,sql:{}".format(sql)) log.exception(e) def explain_sql(self, sql): """查看sql性能""" type_list = ['system', 'const', 'eq_ref', 'ref', 'fulltext', 'ref_or_null', 'index_merge', 'unique_subquery', 'index_subquery', 'range'] try: execute = self.conn.execute("explain " + sql) value = execute.fetchone() if value[3] in type_list: return True return False except Exception as e: log.error("未查询到数据库,sql:{}".format(sql)) log.exception(e) return False def fetch_one(self, sql): """查询sql语句返回的第一条数据""" try: assert self.explain_sql(sql), 'sql语句性能未达标' execute = self.conn.execute(sql) value = execute.fetchone() return value[0] except Exception as e: log.error("未查询到数据库,sql:{}".format(sql)) log.exception(e) def fetch_one_with_index(self, add_index_sql, sql, drop_index_sql): """创建索引,查询sql语句返回的第一条数据""" self.execute(add_index_sql) value = self.fetch_one(sql) self.execute(drop_index_sql) return value
这篇关于mysql查看查询语句性能explain的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-04部署MySQL集群项目实战:新手入门教程
- 2024-11-04如何部署MySQL集群资料:新手入门指南
- 2024-11-02MySQL集群项目实战:新手入门指南
- 2024-11-02初学者指南:部署MySQL集群资料
- 2024-11-01部署MySQL集群教程:新手入门指南
- 2024-11-01如何部署MySQL集群:新手入门教程
- 2024-11-01部署MySQL集群学习:新手入门教程
- 2024-11-01部署MySQL集群入门:新手必读指南
- 2024-10-23BinLog入门:新手必读的MySQL二进制日志指南
- 2024-10-23Binlog入门:MySQL数据库的日志管理指南