Python Script: Optimize mysql tables

Hello Friends,

Below is the script for optimizing database This will decrease the size of tables in most of the cases. I have used python 2.x for this:
-----------------------------------------------------------------------------------------------------------
import os
db = raw_input ( 'Enter the name of the table ')

cmd1 = 'mysql -u root -purpassword android -e "select (data_length+index_length)/power(1024,2) MB from information_schema.tables where table_schema=\'android\' and table_name=\'' + db + '\' ;"'


cmd2 = 'mysql -u root -purpassword android -e "create table ' + db +'_COPY like ' +db + '; " '


cmd3 = 'mysql -u root -purpassword android -e "alter table ' + db + '_COPY disable keys ; " '


cmd4 = 'mysql -u root -purpassword android -e "insert into '+db + '_COPY select * from ' + db + ' ; " '


cmd5 = 'mysql -u root -purpassword android -e "alter table ' +db+ '_COPY enable keys; " '


cmd6 = 'mysql -u root -purpassword android -e "RENAME TABLE ' +db+ ' TO ' +db+'_delete ; " '


cmd7 = 'mysql -u root -purpassword android -e "RENAME TABLE ' +db +'_COPY TO ' +db+ ' ; " '


print 'The size before optimization'
os.system(cmd1)
os.system(cmd2)
os.system(cmd3)
os.system(cmd4)
os.system(cmd5)
os.system(cmd6)
os.system(cmd7)

print 'The size after optimization'
os.system(cmd1)

---------------------------------------------------------------------------------------------

Notes:

1. Replace your password with urpassword
2. android is database name
3. 'db' is the variable where your tables name is stored. 

Comments