1. 程式人生 > >mysql profiling的使用與sql分析

mysql profiling的使用與sql分析

mysql在5.0.3版本之後添加了profiling來進行效能分析

首先進入資料庫

show profiles;

mysql預設是關閉的,也就是OFF

需要設定成1開啟,也就是ON,注意設定以後退出視窗之後會還原,要永久生效貌似需要重啟mysql才行

檢視是否開啟:

開啟:set profiling=1

在這之後每次執行的sql語句都會被記錄。

然後可以檢視具體每個sql的具體情況,執行時間、CPU消耗等

新增測試資料測試:

我自己添加了測試100W+的資料,資料內容亂寫的。本來想一次新增1000W的,電腦記憶體不夠異常了。

測試資料程式碼:

@Test
	public void add() {
		java.sql.Connection conn = null;
		java.sql.PreparedStatement pstm = null;
		ResultSet rt = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mypinyu?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false",
					"root", "
[email protected]
"); String sql = "INSERT INTO sys_operation_log" + "(clazz,function,level,logger,message,create_date,ip,user_id,create_user_name,creater,type) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?)"; pstm = conn.prepareStatement(sql); conn.setAutoCommit(false); Long startTime = System.currentTimeMillis(); Random rand = new Random(); int a, b, c, d; for (int i = 1; i <= 1000000; i++) { a = rand.nextInt(10); b = rand.nextInt(10); c = rand.nextInt(10); d = rand.nextInt(10); pstm.setString(1, "com.pinyu.system.web.controller.LoginController"); pstm.setString(2, "login"+i); pstm.setString(3, "OPERATING"); pstm.setString(4, "com.pinyu.system.web.controller.LoginController"); pstm.setString(5, "xxxxxxxxxx_" + "188" + a + "88" + b + c + "66" + d); pstm.setDate(6, new java.sql.Date(System.currentTimeMillis())); pstm.setString(7, "171.221.144.197"+"."+a+b+c+d); pstm.setString(8, "4"); pstm.setString(9, "admin"+i); pstm.setString(10, "ypp哈哈"+i); pstm.setString(11, "OPERATING"); pstm.addBatch(); } pstm.executeBatch(); conn.commit(); Long endTime = System.currentTimeMillis(); System.err.println("OK,用時:" + (endTime - startTime)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (pstm != null) { try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } }

上面一次新增100W資料用了150秒,還能接受。表字段在10個左右

現在查詢這張表資料,加上之前新增的測試資料,一共有120W+的測試資料。沒有用欄位名,直接*查詢。看看sql的具體執行情況

執行了sql語句:select * from sys_operation_log where message like '%admin%';

接下來肯定是個漫長的等待過程,沒用到索引,全表掃描等,資料量百萬級,肯定不會快,等吧,目的主要分析profiles

再次執行命令:show profiles;

4是執行的sql語句

show profile all for query 4檢視該sql所有執行資訊

裡面每一項,網上資料很多這裡不一一介紹了。

測試完畢,關閉引數

set profiling=0

退出命令視窗。