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

Java程序调用系统命令进行mysql数据库的备份与还原(方式二)
    第二种方式:

数据备份:
public class dbbackup {

public static void backup(string dbname,string file){
   string user = "root"; // 数据库帐号
    string password = "123456"; // 登陆密码
    string database = dbname; // 需要备份的数据库名
    string filepath = file; // 备份的路径地址
    //mysql命令的路径
    string mysqlpath="c:/program files/mysql/mysql server 5.1/bin/";
    try{
          runtime rt = runtime.getruntime();
          process child = rt.exec(mysqlpath+"mysqldump  -u"+user+" -p"+password+" "+database);
          inputstream in = child.getinputstream();// 控制台的输出信息作为输入流
          inputstreamreader isr = new inputstreamreader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8,否则从流中读入的是乱码
            string instr;   
          stringbuffer sb = new stringbuffer("");   
          string outstr; 
          // 组合控制台输出信息字符串   
            bufferedreader br = new bufferedreader(isr);
          while ((instr = br.readline()) != null) {   
                sb.append(instr + "\r\n");   
          }
          outstr = sb.tostring();//备份出来的内容是一个字条串
            fileoutputstream fout = new fileoutputstream(filepath);
          outputstreamwriter writer = new outputstreamwriter(fout, "utf8");
           writer.write(outstr);//写文件   
            // 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免   
            writer.flush(); 
           // 别忘记关闭输入输出流   
              in.close();   
            isr.close();   
            br.close();   
            writer.close();   
            fout.close();
    }
    catch(exception e){
         e.printstacktrace();
    }
}

}



数据还原:
public class dbupload {

   private static string databases;
   static{
       querybuilder qb=new querybuilder("show databases;");
       datatable dt=qb.executedatatable();
       stringbuffer court=new stringbuffer("");
       if(dt.getrowcount()>0){
for(int i=0;i<dt.getrowcount();i++){
   if(i==0){
court.append(dt.ge