Recently I wanted to find out the total size of a schema in a MySQL database. I searched for it but can't really find it. So, I wrote something on my own, really simple which doesn't really bother about a lot of error conditions. But I think that's ok, I mean really this is not a project. I am posting my code here now, feel free to optimize it and tweak it to your own requirement and let me know if you have a better solution :-)
#!/usr/bin/python
"""Calculates the total size of a MySQL database schema approximately."""
import MySQLdb
import getpass
def main():
db_host = raw_input('Host name: ')
schema_name = raw_input('Schema name: ')
user_name = raw_input('User name: ')
password = getpass.getpass('DB Password: ')
db_conn = MySQLdb.connect(host=db_host, user=user_name,
passwd=password, db=schema_name)
db_cursor = db_conn.cursor(MySQLdb.cursors.DictCursor)
db_cursor.execute('show table status')
rows = db_cursor.fetchall()
total_size = 0
for row in rows:
data_length = row['Data_length']
if data_length is None:
data_length = 0
index_length = row['Index_length']
if index_length is None:
index_length = 0
total_size = total_size + data_length + index_length
print '------------------------'
print 'Total size: %s KB.' % str(total_size / 1024)
db_conn.close()
if __name__ == '__main__':
main()
I didn't add any exception handling code, I thought it would clutter the actual code I wanted to show.


0 comments:
Post a Comment