这里直接上代码了,应该都能看懂:
//用于备份的cmd命令:mysqldump -hIP地址 -u用户 -p密码 数据库 表 > F:/home/publicApp.sql --备份到F盘
/*
方法参数:
port:数据库IP(例:192.168.1.1) 不用加端口号
username:数据库账号(例:root)
password:数据库密码(例:123456)
databasename:数据库名称(例:public_app)
tabname:数据库表名称(例:""或" sys_user")
filePath:备份文件存放路径(例:F:/home)
sqlname:备份文件名称(例:publicApp)
注:tabname为可选参数
1.整库备份时该参数设置为空字符串即可:""
2.备份数据库中指定的表时,参数为表名称,注意表名称前加空格:" sys_user"
3.多张表之间空格连接即可:" sys_user sys_role sys_menu"
*/
//备份到指定路径下
public static void dataBaseCopy(String port,String username,String password,String databasename,String tabname,String filePath,String sqlname) {
File file = new File(filePath);
if ( !file.exists() ){
file.mkdir();
}
File datafile = new File(file+File.separator+sqlname+".sql");
if( datafile.exists() ){
System.out.println(sqlname+"文件名已存在,请更换文件名!");
return ;
}
try {
//拼接cmd命令
Process exec = Runtime.getRuntime().exec("cmd /c mysqldump -h"+port+" -u"+username+" -p"+password+" "+databasename+tabname+" > "+datafile);
//exec.waitFor() 返回0为成功,其他值为失败。
//一般失败原因:1.参数错误 2.账号密码错误 3.文件路径错误
if( exec.waitFor() == 0){
log.info("数据库备份成功,备份路径为:"+datafile);
}
} catch (IOException | InterruptedException e) {
log.info("数据库备份失败,执行cmd命令出错!");
}
}
//恢复到数据库中
public static void dataBaseRegain(String port,String username,String password,String databasename,String filePath,String sqlname) {
File datafile = new File(filePath+File.separator+sqlname+".sql");
if( !datafile.exists() ){
System.out.println(sqlname+"文件不存在,请检查文件路径是否正确!");
return ;
}
try {
//拼接cmd命令
Process exec = Runtime.getRuntime().exec("cmd /c mysql -h"+port+" -u"+username+" -p"+password+" "+databasename+" < "+datafile);
if( exec.waitFor() == 0){
log.info("数据库还原成功,还原文件为:"+datafile);
}
} catch (IOException | InterruptedException e) {
log.info("数据库还原成功,执行cmd命令出错!");
}
}
如果看不懂上边的代码,或者有其他问题,请留言,或加vx:mengzhaojie0713