欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

通过java备份恢复mysql数据库的实现代码

程序员文章站 2023-12-20 17:23:34
复制代码 代码如下:import java.io.bufferedreader;import java.io.file;import java.io.fileinputst...
复制代码 代码如下:

import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.io.outputstreamwriter;

public class test {
    public static void main(string[] args) throws ioexception{
        backup("d:\\\\d.sql");
        recover("d:\\\\d.sql");
    }
    public static void backup(string path) throws ioexception{
        runtime runtime = runtime.getruntime();
        //-u后面是用户名,-p是密码-p后面最好不要有空格,-family是数据库的名字
        process process = runtime.exec("mysqldump -u root -p123456 family");
        inputstream inputstream = process.getinputstream();//得到输入流,写成.sql文件
        inputstreamreader reader = new inputstreamreader(inputstream);
        bufferedreader br = new bufferedreader(reader);
        string s = null;
        stringbuffer sb = new stringbuffer();
        while((s = br.readline()) != null){
            sb.append(s+"\\r\\n");
        }
        s = sb.tostring();
        system.out.println(s);
        file file = new file(path);
        file.getparentfile().mkdirs();
        fileoutputstream fileoutputstream = new fileoutputstream(file);
        fileoutputstream.write(s.getbytes());
        fileoutputstream.close();
        br.close();
        reader.close();
        inputstream.close();
    }
    public static void recover(string path) throws ioexception{
        runtime runtime = runtime.getruntime();
        //-u后面是用户名,-p是密码-p后面最好不要有空格,-family是数据库的名字,--default-character-set=utf8,这句话一定的加
        //我就是因为这句话没加导致程序运行成功,但是数据库里面的内容还是以前的内容,最好写上完成的sql放到cmd中一运行才知道报错了
        //错误信息:
        //mysql: character set 'utf-8' is not a compiled character set and is not specified in the '
        //c:\\program files\\mysql\\mysql server 5.5\\share\\charsets\\index.xml' file error 2019 (hy000): can't
        // initialize character set utf-8 (path: c:\\program files\\mysql\\mysql server 5.5\\share\\charsets\\),
        //又是讨人厌的编码问题,在恢复的时候设置一下默认的编码就可以了。
        process process = runtime.exec("mysql -u root -p123456 --default-character-set=utf8 family");
        outputstream outputstream = process.getoutputstream();
        bufferedreader br = new bufferedreader(new inputstreamreader(new fileinputstream(path)));
        string str = null;
        stringbuffer sb = new stringbuffer();
        while((str = br.readline()) != null){
            sb.append(str+"\\r\\n");
        }
        str = sb.tostring();
        system.out.println(str);
        outputstreamwriter writer = new outputstreamwriter(outputstream,"utf-8");
        writer.write(str);
        writer.flush();
        outputstream.close();
        br.close();
        writer.close();
    }
}

上一篇:

下一篇: