#!/bin/python

#coding=utf-8

import MySQLdb

import time

import sys

import MySQLdb.cursors

# 加上字符集参数,防止中文乱码

print "---------TOP OS SLAVE 10--------"

conn = MySQLdb.connect(host="XXXX",db="mysql",user="user",passwd="password",port=338

0,charset="utf8")

cursor = conn.cursor() 

query = "select distinct t.user_host,t.sql_text from mysql.slow_log t  where t.query_time>5 and t.start_time>=SUBDATE(CURDATE(),DATE_FORMAT(CURDATE(),'%w')+3) and t.start_time

cursor.execute(query)

r = cursor.fetchall()

for a in r:          

   user_host =a[0]

   sql_text =a[1]                 

   print "\n"

   print "%s\t%s" %(user_host,sql_text) 

conn.close()

以数组形式输出查询结果。

函数形式多组查询

#!/bin/python

#coding=utf-8

import MySQLdb

import time

import sys

import MySQLdb.cursors


def select():   #定义函数

    query = "select distinct t.user_host,t.sql_text from mysql.slow_log t  where t.query_time>5 and    

    t.start_time>=SUBDATE(CURDATE(),DATE_FORMAT(CURDATE(),'%w')+3) and t.start_time

ATE_FORMAT(CURDATE(),'%w')-4) ORDER BY t.query_time DESC limit 10"

    cursor.execute(query)

    r = cursor.fetchall()

    for a in r:

      user_host =a[0]

      sql_text =a[1]

      print "%s\t%s" %(user_host,sql_text)

      print "\n"

    conn.close()


print('\033[35m')

print "---------TOP OS SLAVE 10--------"

print('\033[0m')

conn=MySQLdb.connect(host="xxxxx",db="mysql",user="user",passwd="password",port=3380,charset="utf8")

cursor = conn.cursor()

select()


print('\033[35m')

print "---------TOP RETAIL SLAVE 10--------"

print('\033[0m')

conn=MySQLdb.connect(host="xxxxxx",db="mysql",user="user",passwd="password",port=3382,charset="utf8")

cursor = conn.cursor()

select()