首页 > 代码库 > MySQL备份还原

MySQL备份还原

MySQL备份还原 简单测试示例

注:这里为了方便,将数据库名称、用户名、密码、备份的文件名称、位置和还原的文件名称、位置硬编码

  在实际中,建议写入配置文件,以下为测试示例代码

 

//备份
	@Test
	public void backup1() throws IOException{
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			// dos 需要执行的命令 指定MySQL用户名、密码和数据库名称
			String cmd = "cmd /c mysqldump -uroot -p123456 cms01";
			Process process =  Runtime.getRuntime().exec(cmd);
			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			//备份到F盘根目录
			writer = new BufferedWriter(new FileWriter("f://b.sql"));
			String str = "";
			while ((str = reader.readLine()) != null) {
				writer.write(str);
				writer.newLine();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			writer.close();
			reader.close();
		}
	}
	
	//还原
	@Test
	public void backup2() throws IOException{
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			// dos 需要执行的命令 指定MySQL用户名、密码和数据库名称
			String cmd = "cmd /c mysql -uroot -p123456 cms01";
			Process process =  Runtime.getRuntime().exec(cmd);
			writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
			//原文件所在位置
			reader = new BufferedReader(new FileReader("f://b.sql"));
			String str = "";
			while ((str = reader.readLine()) != null) {
				writer.write(str);
				writer.newLine();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			reader.close();
			writer.close();
		}
	}

  

 

  

 

MySQL备份还原