python始めました

プログラムのお勉強と言うことで、pythonに取り組み出しました。文法はよくわからないんですが、なんか、きれいにPGかける気がしますね。

とりあえず、MySQLに含まれるInnodb/MyISAMの全テーブルを抽出し、最適化するスクリプトをPythonで書いてみましたので、掲載します。かるくしょぼいです。あとはこれをCRONで定期的に流すようにしますか。

#!/usr/bin/env python

import sys
import MySQLdb

HOST = "127.0.0.1"
USER = "root"
PASS = "hogehoge"
DB = "mysql"

try:
    con = MySQLdb.connect(user = USER, passwd = PASS, db = DB)
    cursor = con.cursor()

    sql = "show databases"
    cursor.execute(sql)
    result = cursor.fetchall()

    for d in result:
        if d[0] == 'information_schema' or d[0] == 'mysql':
            continue

        sql = "show table status from %s" % d

        cursor.execute(sql)
        result = cursor.fetchall()

        for t in result:
            sql = ""
            if t[1] == 'InnoDB':
                sql = "ALTER TABLE %s.%s Engine = InnoDB" % (d[0],t[0])
            elif t[1] == 'MyISAM':
                sql = "OPTIMIZE TABLE  %s.%s" % (d[0],t[0])
            else:
                continue

            cursor.execute(sql)
            result = cursor.fetchall()
            print result

    con.close()

except MySQLdb.Error, e:
    print "Unexpected error %d %s" %  (e.args[0], e.args[1])
    sys.exit(1)

exit(0)
This entry was posted in プログラム. Bookmark the permalink.

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt="">