pythonRegex抽取mysql慢查詢sql本身,de-parameterize,將參數值改為?

來源:互聯網
上載者:User

標籤: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替換。數字很容易,字串需要考慮

  1. 最基本的,替換數字可以用r"\b\d+\b" 獨立的一個或多個連續數字,這樣不會替換如col1等對象中的數字
  2. 簡單地,字串可以用r"‘[^‘]*‘" 表示2個‘之間所有非‘的連續字元,這樣可以適用大多數情況,除了字串有空格的,比如‘a   bdf c‘就不行了
  3. 最嚴謹的方式,按‘對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,將參數值改為?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.