<< Welcome to the Scorpion Software .ro Blog | Home | Java code to save file on FTP server >>

Java code to backup MySQL database

The command line syntax to backup a MySQL database is:


mysqldump -u [username] -p [password] [databasename] > [backupfile.sql]


e.g.: mysqldump -u root -p admin testDB > testDB.sql


http://www.devshed.com/c/a/MySQL/Backing-up-and-restoring-your-MySQL-Database/


Java code:


String[] command = new String[] { "mysqldump", "--user=" + mySQLUsername,

"--password=" + mySQLPassword, "--databases", schema, "-r",

backupPath + "/" + filename};


Runtime runtime = Runtime.getRuntime();

Process process = null;

try {

process = runtime.exec(command);

} catch (IOException e) {

e.printStackTrace();

}

try {

process.waitFor();

} catch (InterruptedException e) {

e.printStackTrace();

}



schema – database name

backupPath – path where you will make the .sql file

filename – name of the .sql file



Accessing newly created database right away:

Creating the sql script takes some time. If you access the file right away and the physical file hasn't been created yet you will get a FileNotFoundException.


Solution:

Make the current thread wait until the process running the exec method finishes.