java在liunx下备份mysql数据,恢复数据
备份数据
public static void exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException { File saveFile = new File(savePath); if (!saveFile.exists()) {// 如果目录不存在 saveFile.mkdirs();// 创建文件夹 } if(!savePath.endsWith(File.separator)){ savePath = savePath + File.separator; } PrintWriter printWriter = null; BufferedReader bufferedReader = null; try { printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8")); Process process = Runtime.getRuntime().exec(" mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName); InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8"); bufferedReader = new BufferedReader(inputStreamReader); String line; while((line = bufferedReader.readLine())!= null){ printWriter.println(line); } printWriter.flush(); if(process.waitFor() == 0){//0 表示线程正常终止。 System.out.println("数据库成功备份!!!"); } }catch (IOException e) { e.printStackTrace(); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (printWriter != null) { printWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } System.out.println("数据库备份失败!!!"); }
恢复数据
public static void dbRestore(String ip,String port,String root,String pwd,String dbName,String filePath,String fileName){ StringBuilder sb = new StringBuilder(); sb.append("mysql"); sb.append(" -h "+ip); sb.append(" -P"+port); sb.append(" -u"+root); sb.append(" -p"+pwd); sb.append(" "+dbName+" --default-character-set=utf8 <"); sb.append(" "+fileName); System.out.println("命令为:"+sb.toString()); System.out.println("开始还原数据"); String result = null; try { String[] cmd = new String[]{sb.toString()}; Process ps = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","cd "+filePath+";"+sb.toString()}); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sbs = new StringBuffer(); String line; while ((line = br.readLine()) != null) { //执行结果加上回车 sbs.append(line).append("\n"); } System.out.println("结果:"+sbs.toString()); } catch (Exception e) { e.printStackTrace(); } System.out.println("还原成功!"); }
执行方法
public static void main(String[] args) throws Exception { //备份数据库 exportDatabaseTool("数据库ip地址", "账号", "密码", "文件存储路径/", "文件名称.sql", "数据库名称"); //恢复数据库 dbRestore("数据库ip地址","数据库端口","账号","密码","数据库名称","文件存储地址","文件名称.sql"); }