SpringBoot导出数据库sql文件

533 阅读1分钟

在后台页面上导出数据库文件,即通过 mysqldump 数据库为 sql 文件,然后下载下来

直接上代码

  1. /**
  2. * 下载SQL
  3. *
  4. * @param response
  5. * @throws IOException
  6. */
  7. @RequestMapping(value = "/exportSql", method = RequestMethod.GET)
  8. public void downloadFile(
  9. HttpServletResponse response) throws IOException {
  10. String exportPath = mysqldump();
  11. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
  12. ``
  13. InputStream f = new FileInputStream(new File(exportPath));
  14. response.reset();
  15. response.setContentType("application/x-msdownload;charset=utf-8");
  16. response.setHeader("Content-Disposition", "attachment;filename=" + sdf.format(new Date()) + ".sql");//下载文件的名称
  17. ServletOutputStream sout = response.getOutputStream();
  18. BufferedInputStream bis = null;
  19. BufferedOutputStream bos = null;
  20. try {
  21. bis = new BufferedInputStream(f);
  22. bos = new BufferedOutputStream(sout);
  23. byte[] buff = new byte[2048];
  24. int bytesRead;
  25. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  26. bos.write(buff, 0, bytesRead);
  27. }
  28. bos.flush();
  29. bos.close();
  30. bis.close();
  31. } catch (final IOException e) {
  32. throw e;
  33. } finally {
  34. if (bis != null) {
  35. bis.close();
  36. }
  37. if (bos != null) {
  38. bos.close();
  39. }
  40. }
  41. }
  42. ``
  43. public static String mysqldump() {
  44. Runtime runtime = Runtime.getRuntime();
  45. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
  46. ``
  47. String exportPath = "/www/mysqldump/" + sdf.format(new Date()) + ".sql";
  48. String command = getExportCommand(exportPath);
  49. // 这里其实是在命令窗口中执行的 command 命令行
  50. try {
  51. runtime.exec(command);
  52. return exportPath;
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. return null;
  57. }
  58. ``
  59. // 得到导出数据的命令行语句
  60. private static String getExportCommand(String exportPath) {
  61. StringBuffer command = new StringBuffer();
  62. String username = "root";// 用户名
  63. String password = "123456";// 密码
  64. String host = "localhost";// 导入的目标数据库所在的主机
  65. String port = "3306";// 使用的端口号
  66. String exportDatabaseName = "house_key";// 导入的目标数据库的名称
  67. String MysqlPath = "/www/server/mysql/bin/"; //路径是mysql中
  68. // 注意哪些地方要空格,哪些不要空格
  69. command.append(MysqlPath).append("mysqldump -u").append(username).append(" -p").append(password)// 密码是用的小p,而端口是用的大P。
  70. .append(" -h").append(host).append(" -P").append(port).append(" ").append(exportDatabaseName)
  71. .append(" -r ").append(exportPath);
  72. return command.toString();