日期:2014-05-16  浏览次数:20478 次

java 中关于备份和还原mysql数据库
-----------------------------备份数据库-----------------------------
/**
* 传入存储路径备份数据库
* @throws IOException  path为 备份为xxx.sql的路径
*/
public void backupdatabase(String path) throws IOException{
Runtime rt = Runtime.getRuntime();
// 调用 调用mysql的安装目录的命令
Process ps= rt.exec("mysqldump -h localhost -u数据库用户名 -p数据库密码  需要备份的数据库名字");
// 设置导出编码为utf-8。这里必须是utf-8
// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
InputStream in= ps.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader ir= new InputStreamReader(in,"utf-8"); // 设置输出流编码为utf-8。这里必须是utf-8,否则从流中读入的是乱码
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
// 组合控制台输出信息字符串
BufferedReader br = new BufferedReader(ir);
while((inStr=br.readLine())!=null){
sb.append(inStr+"\r\n");
}
outStr= sb.toString();
// 要用来做导入用的sql目标文件:
FileOutputStream fo=new FileOutputStream(path);
OutputStreamWriter osw = new OutputStreamWriter(fo,"utf-8");
osw.write(outStr);
osw.flush();
in.close();
ir.close();
br.close();
osw.close();
fo.close();


---------------------------还原数据库-------------------------------

public String load(){
try {
String fPath=ServletActionContext.getServletContext().getRealPath("")+"/backupDatabase/"+"iccafe 20121206 1024.sql";//需要还原的数据库路径
Runtime rt= Runtime.getRuntime();
Process ps= rt.exec("mysql -u"+this.getUserName()+" -p"+this.getPassWord()+" iccafejshopactive");
OutputStream out = ps.getOutputStream();
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath),"utf-8"));
while ((inStr = br.readLine()) != null) {
    sb.append(inStr + "\r\n");
   }
   outStr = sb.toString();
//    System.out.println(outStr);
   OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8");
   writer.write(outStr);
   writer.flush();
   out.close();
   br.close();
   writer.close();
   this.setFlag(true);
   return "json";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.setFlag(false);
return "json";
}

提示:
实现以上的功能首先要配置mysql环境变量。
设置mysql的环境变量(在path中添加%MYSQL_HOME%\bin),重启电脑。


备份语句:mysql> SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',' from db_testtemp where std_state='1';Query OK, 1 row affected (0.00 sec)mysql> SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',' from db_testtemp ;Query OK, 2 rows affected (0.00 sec)只生成一个只有数据的.txt:SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',' lines terminated by '\r\n' from db_testtemp ;只生成一个只有数据的.txt:mysqldump -uroot -pncae2010 -w "std_state='1'" -T D:\data --no-create-info --fields-terminated-by=, exam db_testtemp生成一个创建数据库语句的.sql,一个只有数据的.txt:mysqldump -uroot -pncae2010 -w "std_state='1'" -T D:\data --fields-terminated-by=, exam db_testtemp只生成insert语句:mysqldump -uroot -pncae2010 -w "std_state='1'" -t exam db_testtemp > D:\data\a.sql