java mysql exe_windows下Java调用mysql的客户端备份和恢复

这种东西没啥好聊的,其实就是Java执行dos界面下的命令,不过有些要注意就是了,真实dos下面的命令和java调用的windows系统的接口其实还是有一点不同。

/**

* @param hostIP ip地址,可以是本机也可以是远程

* @param userName 数据库的用户名

* @param password 数据库的密码

* @param savePath 备份的路径

* @param fileName 备份的文件名

* @param databaseName 需要备份的数据库的名称

* @return*/

public staticboolean backup(String hostIP, String userName, String password, String savePath, String fileName,

String databaseName) {

fileName+=".sql";

File saveFile= newFile(savePath);if (!saveFile.exists()) {//如果目录不存在

saveFile.mkdirs();//创建文件夹

}if (!savePath.endsWith(File.separator)) {

savePath= savePath +File.separator;

}//拼接命令行的命令

StringBuilder stringBuilder = newStringBuilder();

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);

System.out.println(stringBuilder.toString());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 staticboolean recover(String filepath,String ip,String database, String userName,String password) {

String stmt1= "mysqladmin -h"+ip+"-u"+userName+"-p"+password+"create"+database;

String stmt2= "cmd /k mysql -h"+ip+"-u"+userName+"-p"+password+" "+database+"

Runtime.getRuntime().exec(stmt1);

System.out.println(stmt1);

Runtime.getRuntime().exec(stmt2);

System.err.println(stmt2);

System.out.println("数据已从" + filepath + "导入到数据库中");

}catch(IOException e) {

e.printStackTrace();return false;

}return true;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值