备份数据库的代码:
/**
* mysql数据库备份
*
* @param savePath
* @param fileName
* @param hostIP
* @param userName
* @param passWord
* @param databaseName
*/
public static void backup(String savePath, String fileName, String hostIP,
String userName, String passWord, String databaseName) {
try {
Runtime rt = Runtime.getRuntime();
System.out.println("备份开始······");
Process child = rt.exec("mysqldump -h " + hostIP + " -u" + userName
+ " -p" + passWord + " " + databaseName);
InputStream in = child.getInputStream();
InputStreamReader xx = new InputStreamReader(in, "utf-8");
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(xx);
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
File saveFile = new File(savePath);
if (!saveFile.exists()) {
saveFile.mkdirs();
}
FileOutputStream fout = new FileOutputStream(savePath + "/"
+ fileName + ".sql");
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf-8");
writer.write(outStr);
writer.flush();
in.close();
xx.close();
br.close();
writer.close();
fout.close();
System.out.println("");
System.out.println("备份成功······");
} catch (Exception e) {
e.printStackTrace();
System.out.println("备份失败······");
}
}
还原数据库的代码:
/**
* Mysql数据库的还原
*
* @param fPath
* @param hostIP
* @param userName
* @param passWord
* @param databaseName
*/
public static void load1(String fPath, String hostIP, String userName,
String passWord, String databaseName) {
try {
System.out.println("还原开始·······");
// String fPath = "c:/test.sql";
Runtime rt = Runtime.getRuntime();
// 调用mysql的cmd命令
Process child = rt.exec("mysql -u" + userName + " -p" + passWord
+ " " + databaseName);
OutputStream out = child.getOutputStream();
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(fPath), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
writer.flush();
out.close();
br.close();
writer.close();
System.out.println("");
System.out.println("还原成功······");
} catch (Exception e) {
e.printStackTrace();
System.out.println("还原失败······");
}
}
测试代码:
public static void main(String args[]) throws IOException {
/**************** 测试Mysql数据库的备份begin **************************************/
/*String hostIP = "localhost";
String userName = "root";
String passWord = "root";
String databaseName = "db_test";
String savePath = "F:/backup";
String fileName = "db_test11";
String fPath = "F:/backup/db_test.sql";
backup(savePath, fileName, hostIP, userName, passWord, databaseName);
load1(fPath, hostIP, userName, passWord, databaseName);*/
/******************************* 测试Mysql数据库的备份end **************************************/
}