Reply to comment
MySQL check & repair script
Submitted by vladimir on Sat, 08/01/2009 - 11:17Recommended to run after every forced shutdown and periodically. Especially useful for large number of databases with MyISAM tables.
Requires: Python 2.x and MySQLdb (mysql python module)
#!/usr/bin/env python ######################################### # Check all tables in all mysql databases # # Written by Vladimir Rusinov <vladimir@greenmice.info>, http://greenmice.info/ # # Reqirements: # Python 2.x (tested with 2.4) # MySQLdb ######################################### # Settings: host="localhost" username="root" password="" exclude_dbs = ('information_schema', ) ######################################### # code import sys from optparse import OptionParser import MySQLdb parser = OptionParser() parser.add_option("-f", "--fast", action="store_true", dest="fast", default="False", help="use fast table ckeck") (options, args) = parser.parse_args() check_type="" if options.fast: check_type="FAST" # first, get list of all databases: try: conn = MySQLdb.connect(host = host, user = username, passwd = password, db = "mysql") cursor = conn.cursor() cursor.execute("SHOW DATABASES") dbs = cursor.fetchall() #print dbs conn.close() except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) # now, check every database for (db, ) in dbs: if db in exclude_dbs: continue print "Checking database %s..." % (db, ) try: conn = MySQLdb.connect(host = host, user = username, passwd = password, db = db) cursor = conn.cursor() cursor.execute("SHOW TABLES") tables = cursor.fetchall() for (table, ) in tables: cursor.execute("CHECK TABLE `%s` %s" % (table, check_type)) status = cursor.fetchone()[3] if status not in ['OK', 'Table is already up to date']: print "Checking table %s.%s... %s; RUNNING REPAIR" % (db, table, status) cursor.execute("REPAIR TABLE `%s`" % (table, )) print cursor.fetchone() except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1)
