[知了堂学习笔记]_Java代码实现MySQL数据库的备份与还原

时间:2023-09-05 20:49:38
  • 通常在MySQL数据库的备份和恢复的时候,多是采用在cmd中执行mysql命令来实现。  

  例如:

    mysqldump -h127.0.0.1 -uroot -ppass test > d:/test.sql  ---备份test数据库到 D 盘
    mysql -h127.0.0.1 -uroot -ppass test< test.sql  ---将D备份的数据库脚本,恢复到数据库中

    更多命令参看:http://www.cnblogs.com/xcxc/archive/2013/01/30/2882840.html
  • 今天采用Java代码,来实现数据库的备份。
      • 在cmd调用命令行,其实是调用 mysql安装路径下面的bin目录下面的 msqldump.exe和mysql.exe来完成相应的工作
      • 所以,在java代码中,我们也需要通过调用 mysqldump.exe和mysql.exe来完成备份和恢复的工作  
    • Runtime.getRuntime().exec(String args);  java调用外部软件exe执行命令的api ,具体参看:http://www.cnblogs.com/tohxyblog/p/6501396.html
  • 数据库备份具体代码
/**
* @param hostIP ip地址,可以是本机也可以是远程
* @param userName 数据库的用户名
* @param password 数据库的密码
* @param savePath 备份的路径
* @param fileName 备份的文件名
* @param databaseName 需要备份的数据库的名称
* @return
*/
public static boolean backup(String hostIP, String userName, String password, String savePath, String fileName,
String databaseName) {
fileName +=".sql";
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
} //拼接命令行的命令
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
stringBuilder.append(" --user=").append(userName).append(" --password=").append(password)
.append(" --lock-all-tables=true");
stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ")
.append(databaseName);
try {
//调用外部执行exe文件的javaAPI
Process process = Runtime.getRuntime().exec(stringBuilder.toString());
if (process.waitFor() == 0) {// 0 表示线程正常终止。
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
  • 数据库恢复代码
/**
* @param filepath 数据库备份的脚本路径
* @param ip IP地址
* @param database 数据库名称
* @param userName 用户名
* @param password 密码
* @return
*/
public static boolean recover(String filepath,String ip,String database, String userName,String password) { String stmt1 = "mysqladmin -h "+ip+" -u "+userName+" -p"+password+" create "+database; String stmt2 = "mysql -h "+ip+" -u "+userName+" -p "+password+" "+database+" < " + filepath; String[] cmd = { "cmd", "/c", stmt2 }; try {
Runtime.getRuntime().exec(stmt1);
Runtime.getRuntime().exec(cmd);
System.out.println("数据已从 " + filepath + " 导入到数据库中");
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}