Java backup mysql database

1. Install mysql database, and configure the mysql installation directory bin directory to the system environment variable

2, command

mysqldump -h (IP) - p (port number) - u (user name) - p (password) - default character set = utf8 database name > where to back up to the local disk

Column: mysqldump - h192.168.1.10 - p3308 - uroot - proot -- default character set = utf8 jiegouhua > C: \ users \ administrator \ desktop \ SQL \ aa.sql

3. Java implementation

JAVA RunTime class and Process class are mainly used to implement the operation of command window. It should be noted that no space should be added between - p, - h, - u, - p (password) and the following values, or unpredictable errors will occur.

/**
	 * Java Code to export MySQL database
	 * @param ip MySQL IP address of the server where the database is located
	 * @param host Database port number
	 * @param userName User name required to enter the database
	 * @param password Password required to enter the database
	 * @param databaseName Database name to export
	 * @param savePath Database export file save path
	 * @param fileName Database export file name
	 * @return Return true to indicate successful export, otherwise return 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()) {// If the directory does not exist
			saveFile.mkdirs();// create folder
		}
		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 Indicates that the thread is terminated normally.
				return true;
			}*/
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (printWriter != null) {
					printWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//return false;
	}

 

Keywords: Database MySQL mysqldump Java

Added by puckeye on Sun, 05 Jan 2020 18:32:39 +0200