標籤:mysq targe class pre sql慢查詢 獨立 extract slow 一個
這個問題我提在了 StackOverflow 上,但沒有回答。自己寫吧
我的需求是,將mysql slow queries展現到頁面上。但是如果原始展現,會帶不同參數,不太好group等。其實我們關心的只是sql本身,比如
-- 這倆其實是一條慢查詢select * from a where a>1 and b=‘r‘ and c=3;select * from a where a>2 and b=‘x‘ and c=5;-- 希望能處理到select * from a where a>? and b=‘?‘ and c=?
因為沒有很合適的module,所以得用regrex替換。數字很容易,字串需要考慮
- 最基本的,替換數字可以用r"\b\d+\b" 獨立的一個或多個連續數字,這樣不會替換如col1等對象中的數字
- 簡單地,字串可以用r"‘[^‘]*‘" 表示2個‘之間所有非‘的連續字元,這樣可以適用大多數情況,除了字串有空格的,比如‘a bdf c‘就不行了
- 最嚴謹的方式,按‘對sql劃分數組。這樣所有‘‘裡面的字串都是偶數成員,其他部分奇數成員。替換偶數成員為?就可以了
代碼如下import re
sql = r"select * from a where id=‘aaaaa haha wocao‘ and id1= ‘fff‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99"sql.split("‘")#[‘select * from a where id=‘, ‘aaaaa haha wocao‘, ‘ and id1= ‘, ‘fff‘, ‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99‘]sarr = sql.split("‘")sarr#[‘select * from a where id=‘, ‘aaaaa haha wocao‘, ‘ and id1= ‘, ‘fff‘, ‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99‘]sarr[::2]#[‘select * from a where id=‘, ‘ and id1= ‘, ‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99‘]sarr[1::2]#[‘aaaaa haha wocao‘, ‘fff‘]sarr[1::2]= [‘?‘ for x in sarr[1::2]]sarr#[‘select * from a where id=‘, ‘?‘, ‘ and id1= ‘, ‘?‘, ‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99‘]"‘".join(sarr)#"select * from a where id=‘?‘ and id1= ‘?‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99"sql#"select * from a where id=‘aaaaa haha wocao‘ and id1= ‘fff‘ and xx=1 and a3= 4 and a4=3434343 and a5a>99"
aa = "‘".join(sarr)
re.sub(r"\b\d+\b","?",aa)
#"select * from a where id=‘?‘ and id1= ‘?‘ and xx=? and a3= ? and a4=? and a5a>?"
pythonRegex抽取mysql慢查詢sql本身,de-parameterize,將參數值改為?