工具类:
public class MySqlDatebaseBackupRestore {
/**
* java 实现mysql数据库导出
* @param hostIP mysql所在服务器的地址ip
* @param userName 进入数据库所需要的用户名
* @param password 进入数据库所需要的密码
* @param savePath 数据库导出保存文件的路径
* @param fileName 数据库导出文件名称
* @param databaseName 要导出的数据库名称
* @return
* @throws InterruptedException
*/
public static boolean backupDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {
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);
try {
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;
}
/**
* Java实现MySQL数据库还原
* @param hostIP MySQL数据库所在服务器地址IP
* @param userName 数据库用户名
* @param password 进入数据库所需要的密码
* @param importFilePath 数据库文件路径
* @param sqlFileName 数据库文件名
* @param databaseName 要导入的数据库名
* @return 返回true表示导入成功,否则返回false。
*/
public static boolean restoreDatabaseTool(String hostIP, String userName, String password, String importFilePath, String sqlFileName, String databaseName){
File saveFile = new File(importFilePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if (!importFilePath.endsWith(File.separator)) {
importFilePath = importFilePath + File.separator;
}
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("mysql").append(" -h").append(hostIP);
stringBuilder.append(" -u").append(userName).append(" -p").append(password);
stringBuilder.append(" ").append(databaseName);
stringBuilder.append(" <").append(importFilePath).append(sqlFileName);
try {
Process process = Runtime.getRuntime().exec("cmd /c "+stringBuilder.toString());//必须要有“cmd /c ”
if (process.waitFor() == 0) {// 0 表示线程正常终止。
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
/* public static void main(String[] args) throws InterruptedException {
if (restoreDatabaseTool("192.168.0.113", "root", "123", "D:\\backupDatabase", "2018-03-16.sql", "GHJ")) {
System.out.println("数据库导入成功!!!");
} else {
System.out.println("数据库导入失败!!!");
}
} */
/* public static void main(String[] args){
try {
if (backupDatabaseTool("192.168.0.113", "root", "ROOT", "D:/backupDatabase", "2018-03-16.sql", "mis")) {
System.out.println("数据库成功备份!!!");
} else {
System.out.println("数据库备份失败!!!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} */
public static void main(String[] args) {
getFileName();
}
public static void getFileName() {
String path = "D:/backupDatabase"; // 路径
File f = new File(path);
if (!f.exists()) {
System.out.println(path + " not exists");
return;
}
File fa[] = f.listFiles();
for (int i = 0; i < fa.length; i++) {
File fs = fa[i];
if (fs.isDirectory()) {
System.out.println(fs.getName() + " [目录]");
} else {
System.out.println(fs.getName());
}
}
}
}
说明:在controller层调用上述方法,用户名密码,可以从jdbc属性文件中获取。(详细写法可以看获取配置文件的值工具类)
controller层:
@Controller
public class MysqlBRController {
//配置文件路径
String path="config/jdbc.properties";
//数据库用户名和密码
String username=PropertiesUtil.getByName(path,"jdbc.username");
String password=PropertiesUtil.getByName(path,"jdbc.password");
/**
* 数据库备份
* @return
* @throws Exception
*/
@RequestMapping(value="/backUp",method=RequestMethod.POST,produces="text/html;charset=utf-8")
@ResponseBody
public Object backUp(HttpServletRequest request,HttpServletResponse response) throws Exception{
JSONObject data = new JSONObject();
//数据库导出文件名
String name= new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+".sql";
String url=request.getSession().getServletContext().getRealPath("/sql");
try {
if (MySqlDatebaseBackupRestore.backupDatabaseTool("localhost", username, password, url, name, "rce")) {
//调用文件下载的方法
String fileName = request.getSession().getServletContext().getRealPath("/sql")+"/"+name;
FileUploadUtil.fileDownload(request, response, fileName);
data.put("data", "数据库成功备份!!!");
} else {
data.put("data", "数据库备份失败!!!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
data.put("fileName", name);
data.put("url", url);
return data.toString();
}
/**
* 数据库还原
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping(value="/restore",method=RequestMethod.POST,produces="text/html;charset=utf-8")
@ResponseBody
public Object restore(HttpServletRequest request,MultipartFile file) throws IllegalStateException, IOException{
String path=request.getSession().getServletContext().getRealPath("/sql");
JSONObject data = new JSONObject();
//数据库还原时选择本地文件上传到服务器本地
String fileName=FileUploadUtil.fileUpload(file, path);
//判断是否为sql文件
String sufName=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
if(sufName.endsWith(".sql")){
//数据库导入文件名称
//String fileName=request.getParameter("fileName");
//String url=request.getSession().getServletContext().getRealPath("sql");
if (MySqlDatebaseBackupRestore.restoreDatabaseTool("localhost", username, password, path, fileName, "rce")) {
data.put("data", "数据库导入成功!!");
} else {
data.put("data", "数据库导入失败!!");
}
}else{
data.put(data, "请导入正确的sql文件");
}
return data.toString();
}
}