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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM