java对 mysql数据的备份和还原

来源:互联网 发布:兼职数据录入招聘 编辑:程序博客网 时间:2024/06/06 01:29

前提配置好java环境  安装MYSQL  因为备份与还原调用的mysql自己的命令

import java.io.IOException;


public class Sql {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        backup();

        back();
        Load();
        

    }
    //数据库中的某张表的备份
    public static void backup() {
        String host = "数据库的IP";
        String user = "数据库的用户名";
        String password = "数据库的密码";
        String database = "数据库名称";
        String filepath = "e:\\6.sql";//备份的位置以及名称
        String table = "channel_info";//备份的表的名称

        // String stmt1 = "mysqldump " + database +" -h "+host+ " -u " + user +
        // " -p" +
        // password + " --default-character-set=utf8 --result-file=" + filepath;

        String stmt1 = "mysqldump " + database + " " + table + " -h " + host
                + " -u " + user + " -p" + password
                + " --default-character-set=utf8 --result-file=" + filepath;

        try {
            Runtime.getRuntime().exec(stmt1);
            System.out.println("数据已经导出到" + filepath + "中");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //数据的导入
    
    public static void Load() {
        String host = "要导入的数据库IP";
        String user = "数据库用户名";
        String password = "数据库密码";
        String database = "要导入的数据库名称";
        String filepath = "e:\\6.sql";//调用所要导入的sql文件
        String stmt1 = "cmd /c mysql  -h " + host + " " + database + " -u "
                + user + " -p" + password + " <" + filepath;

        try {
            Runtime.getRuntime().exec(stmt1);
            System.out.println("数据已经导入到" + database + "中");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //数据库备份
    public static void back() {
        String host = "10.0.40.61";
        String user = "root";
        String password = "tvmer";
        String database = "qa_test";
        String filepath = "e:\\6.sql";
        

        String stmt1 = "mysqldump " + database + " -h " + host + " -u " + user
                + " -p" + password
                + " --default-character-set=utf8 --result-file=" + filepath;
        try {
            Runtime.getRuntime().exec(stmt1);
            System.out.println("数据已经导出到" + filepath + "中");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


原创粉丝点击