Tuesday, February 9, 2010

Executing MySQL Scripts in Batch Mode

I wrote a script that would accept a file path and traverse through the directory tree to search for files with extension *.sql and load those sql scripts into MySQL and run them.
My *.sql files are basically scripts that builds database tables. 


Here's what I've done;

################################################################################
#!/bin/sh

# Reads the specified directory and traverses for the sql script files.
# The first argument($1) is the target directory to be searched.

#Read the files in the directory and generate the table creation statements separating them using the semi-colon delimiter
# If there are sub-directories, they will be traversed and all files ending in '.sql' will be processed
source_queries=""
source_command="source "
echo "argument passed $1"

for file in $(find $1 -type f -iname '*.sql'); do
source_queries="${source_queries}${source_command}${file};"
done

# Uncomment to printout generated queries/statements for debugging purposes
# echo "printing statements generated ${source_queries}"

# Connect to the database using the 'stratus' database and execute the query statements generated
# This can be run on the background as well

echo "Executing database tables creation scipt......."
mysql -u myuser --password=mypassword --database=mydatabase -e "${source_queries}"
echo "script completed...."
#################################################################################



Say if there's 1 script file with filename create_person_table.sql under the target directory /opt/db_scripts the resulting mysql command would look like this


mysql -u myuser --password=mypassword --database=mydatabase -e "source /opt/db_scripts/create_person_table.sql"


If there are multiple sql files the clause on the '-e' option would look like this


mysql -u myuser --password=mypassword --database=mydatabase -e "source /opt/db_scripts/create_person_table.sql;source /opt/db_scripts/create_employee_table.sql"







2 comments:

  1. Nobody should be hurt due to an addiction. At on this occasion I was in
    college and sharing a town-home with good friend.
    I'll probably never become accustomed to chatting, in my work room, with someone twelve thousand miles away in Indonesia.

    Feel free to visit my homepage ... Latin Adultery 19

    ReplyDelete
  2. Everything is very open with a clear clarification of the challenges.
    It was definitely informative. Your website is very helpful.
    Many thanks for sharing!

    Here is my site - walking calorie calculator

    ReplyDelete