• 傻瓜式Java操作MySQL数据库备份


    在这里插入图片描述

    前言

      数据库备份是开发工作中经常要做的事情,好处是mysql提供了一个非常好的命令 mysqldump,直接调用它就可以将数据以sql文件的形式备份出来。但是直接写命令非常不方便,遇到定时备份或者指定备份那么就需要代码调用。下面是一个使用java代码调用该命令的小示例:

    mysqldump -u username -p password -h host -P port exportDatabaseName exportPath
    
    • 1

      在进行导出的时候,需要注意命令语句的运行环境,如果已经将mysql安装路径下的bin加入到系统的path变量中,那么在导出的时候可以直接使用命令语句,否则,就需要在执行命令语句的时候加上命令所在位置的路径,即mysql安装路径想的bin下的mysqldump命令。

    存储数据库

    public class DataSyncTransfer {
    	/** MySQL安装目录的Bin目录的绝对路径 */
    	private static String mysqlBinPath = "/usr/local/mysql/bin/";
    	private static String mysqldump = mysqlBinPath + "mysqldump";
    
    	/**
    	 * 备份 MySQL 数据库
    	 * 
    	 * @param clientIp   访问MySQL数据库的主机
    	 * @param port       访问MySQL数据库的端口
    	 * @param userName   访问MySQL数据库的用户名
    	 * @param password   访问MySQL数据库的密码
    	 * @param database   需要备份的数据库,多个数据库之间使用逗号分隔
    	 * @param backupFile 备份文件存放的路径,如果指定路径的文件不存在会自动生成
    	 */
    	public static boolean backupDatabase(String clientIp, int port, String userName, String password, String database,
    			String backupPath) throws Exception {
    		// 当前日期
    		String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    		// 当前时间
    		String currentTime = new SimpleDateFormat("HH-mm-ss").format(Calendar.getInstance().getTime());
    		// 备份文件名
    		String backupFileName = database + "-" + currentDate + "-" + currentTime + ".sql";
    		// 备份文件路径
    		String backupFilePath = backupPath + backupFileName;
    		// 创建备份文件存放目录,如果已经存在则不创建
    		new File(backupPath).mkdirs();
    
    		// 新建命令列表
    		List<String> commandList = new ArrayList<>();
    		// 添加命令:备份 MySQL 数据库
    		commandList.add(mysqldump);
    		// 添加命令参数:MySQL 服务器地址
    		if (StringUtils.isNoneBlank(clientIp)) {
    			commandList.add("--host=" + clientIp);
    		}
    		// 添加命令参数:MySQL 用户名
    		commandList.add("--user=" + userName);
    		// 添加命令参数:备份文件路径
    		commandList.add("--result-file=" + backupFilePath);
    		// 添加命令参数:指定要备份的数据库
    		commandList.add("--databases");
    		// 添加要备份的数据库名称
    		commandList.add(database);
    
    		// 创建进程构建器
    		ProcessBuilder pb = new ProcessBuilder(commandList);
    		// 设置 MySQL 密码
    		pb.environment().put("MYSQL_PWD", password);
    		// 启动进程
    		Process process = pb.start();
    		readStringFromInputStream(process.getInputStream(), backupFilePath);
    		// 等待进程结束
    		int processComplete = process.waitFor();
    
    		if (processComplete == 0) { // 如果进程成功结束
    			return true;
    		} else { // 如果进程没有成功结束
    			return false;
    		}
    	}
    
    	/**
    	 * 存储文件
    	 */
    	private static void readStringFromInputStream(InputStream stream, String backupFilePath) throws IOException {
    		byte[] buff = new byte[128];
    		int n;
    		FileOutputStream fileOutputStream = null;
    		StringBuilder sb = new StringBuilder();
    		try {
    			while ((n = stream.read(buff)) != -1) {
    				sb.append(new String(buff, 0, n));
    			}
    			fileOutputStream = new FileOutputStream(new File(backupFilePath));
    			fileOutputStream.write(sb.toString().getBytes());
    
    		} finally {
    			fileOutputStream.close();
    			stream.close();
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83

    存储数据表

    public class DataSyncTransfer {
    	/** MySQL安装目录的Bin目录的绝对路径 */
    	private static String mysqlBinPath = "/usr/local/mysql/bin/";
    	private static String mysqldump = mysqlBinPath + "mysqldump";
    
    	/**
    	 * 备份数据表
    	 * 
    	 * @param clientIp   访问MySQL数据库的主机
    	 * @param port       访问MySQL数据库的端口
    	 * @param userName   访问MySQL数据库的用户名
    	 * @param password   访问MySQL数据库的密码
    	 * @param database   需要备份的数据库
    	 * @param tableName  需要备份的数据库,多个表之间使用空格分隔
    	 * @param backupFile 备份生成的文件路径,如果指定路径的文件不存在会自动生成
    	 */
    	public static boolean backupTable(String clientIp, int port, String userName, String password, String database,
    			String tableNames, String backupPath) throws Exception {
    		// 根据逗号分隔符,将要备份的数据库名称拆分成数组
    		// String[] tableArr = tableNames.split(",");
    		// 当前日期
    		String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
    		// 当前时间
    		String currentTime = new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime());
    		// 备份文件名
    		String backupFileName = database + "-" + currentDate + currentTime + ".sql";
    		// 备份文件路径
    		String backupFilePath = Paths.get(backupPath, backupFileName).toFile().getPath();
    
    		String command = mysqldump + " -u" + userName + " -p" + password + " " + database + " " + tableNames;
    		Process process = Runtime.getRuntime().exec(command);
    		readStringFromInputStream(process.getInputStream(), backupFilePath);
    
    		// 等待进程结束
    		int processComplete = process.waitFor();
    
    		if (processComplete == 0) { // 如果进程成功结束
    			return true;
    		} else { // 如果进程没有成功结束
    			return false;
    		}
    	}
    
    	/**
    	 * 存储文件
    	 */
    	private static void readStringFromInputStream(InputStream stream, String backupFilePath) throws IOException {
    		byte[] buff = new byte[128];
    		int n;
    		FileOutputStream fileOutputStream = null;
    		StringBuilder sb = new StringBuilder();
    		try {
    			while ((n = stream.read(buff)) != -1) {
    				sb.append(new String(buff, 0, n));
    			}
    			fileOutputStream = new FileOutputStream(new File(backupFilePath));
    			fileOutputStream.write(sb.toString().getBytes());
    
    		} finally {
    			fileOutputStream.close();
    			stream.close();
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
  • 相关阅读:
    从海后丢掉“海后”这个角色说起—— 论VOC对于DTC品牌的重要性
    软件测试/测试开发丨Python异常处理 学习笔记
    【每日一题】 和为 K 的子数组
    Gin+WebSocket实战——在线聊天室WebSocketDemo详细使用教程
    JavaWeb之组件Servlet详解
    ava面试八股文-基础概念二
    css之Flex弹性布局(子项常见属性)
    排序(冒泡、选择、插入、希尔、归并、快速)
    dbeaver下载镜像站
    代码质量与安全 | 想在发布竞赛中胜出?Sonar来帮你
  • 原文地址:https://blog.csdn.net/duleilewuhen/article/details/133420798