欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

【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(); } } }