Restore MySql DB on Windows using Java

MYSQl is the world’s second most widely used open-source relational database management system. MYSQL RDBMS provides the mysql shell to restore the database, We can invoke the mysql command from command Prompt to restore the database, mysql shell can also be invoked from java using the java.lang.Runtime class.
In the example we are going to restore the database using java.lang.RunTime class.
package com.javaartifacts;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class RestoreDbFile {

public static void main(String[] args){


int rscreatedb = -1;

String cmdPath="cmd,exe /c";
String mysqlPath="mysql";
String dbName="nameofDB";
String mysqlFilePath="mySqlFilePath.sql";

String dbUserName="root";
String dbPassword="root@123";
String mysqlURL ="jdbc:mysql://localhost:3306/";

Connection mysqlconn = DriverManager.getConnection(mysqlURL,dbUserName,dbPassword);

Statement stmtcreatedb = mysqlconn.createStatement();
rscreatedb = stmtcreatedb.executeUpdate("CREATE DATABASE IF NOT EXISTS "+dbName);
if(rscreatedb == 1){
System.out.println("Database created successfully");
System.out.println("Unable to create Database");

restoreDB(cmdPath, mysqlPath, dbUserName, dbPassword, dbName, mysqlFilePath);

catch(Exception ex){

public static boolean restoreDB(String cmdPath, String mysqlPath, String dbUserName, String dbPassword, String dbName, String mysqlFilePath) {

boolean status = false;

String executeCmd = cmdPath+" "+mysqlPath+" --user="+dbUserName+" --password="+dbPassword+ " --database="+dbName+" < "+ mysqlFilePath;

Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
InputStream stderr = runtimeProcess.getInputStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String msg = null;
while ( (msg = br.readLine()) != null)
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
status = true;
else {
InputStream stdmsg = runtimeProcess.getErrorStream();
InputStreamReader isrm = new InputStreamReader(stdmsg);
BufferedReader brm = new BufferedReader(isrm);
String msgex = null;
while ( (msgex = brm.readLine()) != null)
status = false;
catch(Exception ex){
status = false;


return status;

To run this program create java Project —> create package(com.javaartifacts) —> create class RestoreDbFile(Copy and paste above code in class file) —> download and paste the mysql jar in lib file

In the Program We are first creating the database by executing the query using the jdbc api.
For succesfully execution we have to set the path of mysql.exe path in Environment variable or supply the full path of mysql.exe.
If there is space in between the directory Path as shown below then we have to supply the full path in double quotes like "\"C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysql.exe\"" in the restoreDB method.