zoukankan      html  css  js  c++  java
  • Java进行数据库导出导入 亲测可用

    /**
    * @param hostIP ip地址,可以是本机也可以是远程
    * @param userName 数据库的用户名
    * @param password 数据库的密码
    * @param savePath 备份的路径
    * @param fileName 备份的文件名
    * @param databaseName 需要备份的数据库的名称
    * @return
    */
    public static boolean backup(String hostIP, String userName, String password, String savePath, String fileName,
    String databaseName) {
    fileName +=".sql";
    File saveFile = new File(savePath);
    if (!saveFile.exists()) {// 如果目录不存在
    saveFile.mkdirs();// 创建文件夹
    }
    if (!savePath.endsWith(File.separator)) {
    savePath = savePath + File.separator;
    }

    //拼接命令行的命令
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
    stringBuilder.append(" --user=").append(userName).append(" --password=").append(password)
    .append(" --lock-all-tables=true");
    stringBuilder.append(" --result-file=").append(savePath+fileName).append(" --default-character-set=utf8 ")
    .append(databaseName);
    System.out.println(stringBuilder.toString());
    try {
    //调用外部执行exe文件的javaAPI
    Process process = Runtime.getRuntime().exec(stringBuilder.toString());
    if (process.waitFor() == 0) {// 0 表示线程正常终止。
    return true;
    }
    } catch (IOException e) {
    e.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return false;
    }

    /**
    * @param filepath 数据库备份的脚本路径
    * @param ip IP地址
    * @param database 数据库名称
    * @param userName 用户名
    * @param password 密码
    * @return
    */
    public static boolean recover(String filepath,String ip,String database, String userName,String password) {

    String stmt1 = "mysqladmin -h "+ip+" -u "+userName+" -p"+password+" create "+database;

     //cmd /k在执行命令后不关掉命令行窗口  cmd /c在执行完命令行后关掉命令行窗口 

    String stmt2 = "cmd /k mysql -h "+ip+" -u"+userName+" -p"+password+" "+database+" < " + filepath;


    try {
    Runtime.getRuntime().exec(stmt1);
    System.out.println(stmt1);

    Runtime.getRuntime().exec(stmt2);

    System.err.println(stmt2);
    System.out.println("数据已从 " + filepath + " 导入到数据库中");
    } catch (IOException e) {
    e.printStackTrace();
    return false;
    }
    return true;
    }

  • 相关阅读:
    《Java TCP/IP Socket 编程 》读书笔记之十一:深入剖析socket——TCP套接字的生命周期
    c++实现二分查找
    hadoop序列化机制与java序列化机制对比
    C、C++中“*”操作符和“后++”操作符的优先级
    poj2774之最长公共子串
    Python之美[从菜鸟到高手]--urlparse源码分析
    (程序员面试题)字符串处理之寻找最大不重复子串
    hdu 4782 Beautiful Soupz
    教程Xcode 下编译发布与提交App到AppStore
    云端的ABAP Restful服务开发
  • 原文地址:https://www.cnblogs.com/blogwangwang/p/10538159.html
Copyright © 2011-2022 走看看