在后台页面上导出数据库文件,即通过 mysqldump 数据库为 sql 文件,然后下载下来
直接上代码
/**
* 下载SQL
*
* @param response
* @throws IOException
*/
@RequestMapping(value = "/exportSql", method = RequestMethod.GET)
public void downloadFile(
HttpServletResponse response) throws IOException {
String exportPath = mysqldump();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
InputStream f = new FileInputStream(new File(exportPath));
response.reset();
response.setContentType("application/x-msdownload;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + sdf.format(new Date()) + ".sql");//下载文件的名称
ServletOutputStream sout = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(f);
bos = new BufferedOutputStream(sout);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bos.flush();
bos.close();
bis.close();
} catch (final IOException e) {
throw e;
} finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
}
}
public static String mysqldump() {
Runtime runtime = Runtime.getRuntime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String exportPath = "/www/mysqldump/" + sdf.format(new Date()) + ".sql";
String command = getExportCommand(exportPath);
// 这里其实是在命令窗口中执行的 command 命令行
try {
runtime.exec(command);
return exportPath;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 得到导出数据的命令行语句
private static String getExportCommand(String exportPath) {
StringBuffer command = new StringBuffer();
String username = "root";// 用户名
String password = "123456";// 密码
String host = "localhost";// 导入的目标数据库所在的主机
String port = "3306";// 使用的端口号
String exportDatabaseName = "house_key";// 导入的目标数据库的名称
String MysqlPath = "/www/server/mysql/bin/"; //路径是mysql中
// 注意哪些地方要空格,哪些不要空格
command.append(MysqlPath).append("mysqldump -u").append(username).append(" -p").append(password)// 密码是用的小p,而端口是用的大P。
.append(" -h").append(host).append(" -P").append(port).append(" ").append(exportDatabaseName)
.append(" -r ").append(exportPath);
return command.toString();
}
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏