Assume your script is "myscript.sql" and its stored in "c:\" then following command can be used to import that script to your database
c:\Program Files\MySQL\MySQL Server 5.1\bin\mysql.exe --host=127.0.0.1 --user=root --password=root < c:/myscript.sql
This same command can be used in Runtime.getRuntime().exec . But when i tried there is some simple issues and its not working properly.So i used another method.
Before that i am assuming that your database script contain more data than in database. So even if i delete database and then import database using database script , i dont loss any data. I am just dropping(removing) current database and importing database from your database script file.
To solve above mentioned Runtime.getRuntime().exec , i created a batch file named "ba.bat" . And stored that batch file in c: drive as "c:\bat.bat". Content of that batch file is given below
%1\mysql.exe --host=%2 --user=%3 --password=%4 < c:/myscript.sql
exit
You can call with following syntax ba.bat arg1 arg2 arg3 arg4
where arg1=path to mysql bin folder example =c:\Program Files\MySQL\MySQL Server 5.1\bin
arg2=mysql host ip address
arg3=mysql username
arg4=mysql password
And the final java program is given below
import java.sql.*;
public class NewClass {
public static void main(String[] args) {
Connection conn = null;
String mysqlPath="c:/Program Files/MySQL/MySQL Server 5.1/bin";
String url = "jdbc:mysql://192.168.100.86/";
String databaseIp="192.168.100.86";
String dbName = "databasename";
java.sql.Statement stmt = null;
String query = "";
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url , userName, password);
stmt = conn.createStatement();
result = null;
String test,input;
stmt.execute("drop database if exists "+dbName);
String fullPathWithArgs ="C:/ba.bat \""+mysqlPath+"\" "+databaseIp+" "+userName+" "+password+"";
Process runtimeProcess =Runtime.getRuntime().exec(fullPathWithArgs);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0)
{
System.out.println("DatabaseManager.restore: Restore Successfull");
}
else
{
System.out.println("DatabaseManager.restore: Restore Failure!");
}
conn.close();
} catch (Exception e) {
System.out.println("exception: " + e.getMessage());
}
}
}
In the above java program i am dropping database and importing database from script.
You must use CREATE DATABASE IF NOT EXISTS in your script.From your question i felt this is what you want. Please let me know in case of any problem or above is not your expected answer.
One more thing if you want to append data to existing database then please delete
stmt.execute("drop database if exists "+dbName);
from java code and also make the required column in your database table to 'unique' ie.. create unique index for required table columns
mysqldump?