【SQL】慢 SQL 的定位方式
最编程
2024-07-06 07:21:30
...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SlowQueryAnalyzer {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/yourdatabase";
String username = "yourusername";
String password = "yourpassword";
try (Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement()) {
String slowQuery = "SELECT * FROM orders WHERE customer_id = 12345 AND order_date > '2023-01-01'";
long startTime = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery(slowQuery);
long endTime = System.currentTimeMillis();
System.out.println("Query executed in " + (endTime - startTime) + " ms");
// 使用 EXPLAIN 分析
ResultSet explainRs = stmt.executeQuery("EXPLAIN " + slowQuery);
while (explainRs.next()) {
System.out.println("id: " + explainRs.getInt("id"));
System.out.println("select_type: " + explainRs.getString("select_type"));
System.out.println("table: " + explainRs.getString("table"));
System.out.println("type: " + explainRs.getString("type"));
System.out.println("possible_keys: " + explainRs.getString("possible_keys"));
System.out.println("key: " + explainRs.getString("key"));
System.out.println("rows: " + explainRs.getInt("rows"));
System.out.println("Extra: " + explainRs.getString("Extra"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
推荐阅读
-
超级集 SQL 模板的使用
-
SQL 中的 DDL 分类 - I. 操作数据库的 DDL 语句
-
关系数据库标准语言 SQL 的数据库系统入门 (I) [超详细]。
-
皮卡丘-Sql-注入 - 基于布尔的盲注
-
常见数据库管理系统(MySQL、Oracle、SQL Server)的特点和区别。
-
基于 SSM 的微信小程序教辅管理系统(研究 1)(源代码 + sql 脚本 + 视频导入教程 + 文档)
-
在 SpringBoot-MybatisPlus 项目中,在控制台中查看 sql 执行日志的方法
-
SQL | 使用单引号查询异常数据以及替换和插入的区别
-
基于SSM+微信小程序的校园二手数字交易平台系统(二手3)(源码+sql脚本+视频导入教程+文档)
-
遇到SQL速度慢时如何定位问题,SQL错误报告 | OceanBase优化实践