一、Java备份mysql数据库
/**
* Java代码实现MySQL数据库导出
* @param ip MySQL数据库所在服务器地址IP
* @param host 数据库端口号
* @param userName 进入数据库所需要的用户名
* @param password 进入数据库所需要的密码
* @param databaseName 要导出的数据库名
* @param savePath 数据库导出文件保存路径
* @param fileName 数据库导出文件文件名
* @return 返回true表示导出成功,否则返回false。
* @throws IOException
*/
public static void exportDatabaseTool(String ip, String host, String userName, String password, String databaseName, String savePath, String fileName) throws IOException {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if(!savePath.endsWith(File.separator)){
savePath = savePath + File.separator;
}
PrintWriter printWriter = null;
BufferedReader bufferedReader = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
Process process = Runtime.getRuntime().exec(" mysqldump -h" + ip + " -P" + host + " -u" + userName + " -p" + password + " --default-character-set=utf8 " + databaseName);
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line = bufferedReader.readLine())!= null){
printWriter.println(line);
}
printWriter.flush();
/*if(process.waitFor() == 0){//0 表示线程正常终止。
return true;
}*/
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//return false;
}
二、Java执行mysql数据库脚本
/**
* 执行SQL脚本文件
* @param ip MySQL数据库所在服务器地址IP
* @param host 数据库端口号
* @param userName 进入数据库所需要的用户名
* @param password 进入数据库所需要的密码
* @param databaseName 要导入的数据库名
* @param filePath SQL脚本文件目录
* @param fileName SQL脚本文件名称
* @throws IOException
*/
public static void runSqlFile(String ip, String host, String userName, String password, String databaseName, String filePath, String fileName) throws IOException{
String cmdarray[] = { "mysql -h" + ip + " -P" + host + " -u" + userName + " -p" + password + " " + databaseName, "source " + filePath + fileName };
Runtime runtime = Runtime.getRuntime();
OutputStream os = null;
OutputStreamWriter writer = null;
try {
Process process = runtime.exec("cmd /c " + cmdarray[0]);//cmd之后执行数组的第一个条件进入数据库
//执行了第一条命令以后已经登录到mysql了
os = process.getOutputStream();
writer = new OutputStreamWriter(os);
writer.write(cmdarray[1]);//向图形界面输出第二第三条命令。中间 \r\n 作用是用来换行的,
writer.flush();
} finally {
try {
if (writer != null) {
writer.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
转载来自:
https://blog.csdn.net/qq_40402648/article/details/81560408
https://blog.csdn.net/qq_40402648/article/details/81670182