Thursday, December 20, 2012

Deleting all rows of all tables of a list of MySQL databases

Like most Java developers, I use the database technology with just enough knowledge of SQL, JPA/JPQL. In one of our application, we have a bunch of mysql databases, and recently, I had a need to clean up the contents of all the databases, all the tables, without deleting the structure. In other words, there was no choice of dropping and recreating databases. Also there was no choice of any UI tools, or not even a choice of writing something from my favorite Java. The only option was shell-script with a headless unix system.

Therefore, I wrote this simple utility in shell to clean-up a list of databases. It may be handy. Enjoy!


#!/bin/sh

cleanup_mysql(){
        read -s -p "Enter MySQL root Password: " mysqlpassword
        db_list="Database1   Database2   Database3   Database4"
        dml="SET foreign_key_checks = 0;"
        for db in $db_list
        do
                echo "Cleaning up database: $db"
                TABLES=`mysql -u root -p$mysqlpassword $db -e 'show full tables where Table_Type = "BASE TABLE"'|awk '{ print $1}'|grep -v '^Tables'`
                for table in $TABLES
                do
                        dml="$dml DELETE FROM $db.$table;"
                done
        done
        dml="$dml SET foreign_key_checks = 1;"
        mysql -u root -p$mysqlpassword --e="$dml"
}
cleanup_mysql

No comments:

Post a Comment