Javaバックアップmysqlデータベース

2177 ワード

1、mysqlデータベースをインストールし、mysqlインストールディレクトリbinディレクトリをシステム環境変数に配置する
2、コマンド
mysqldump-h(IP)-P(ポート番号)-u(ユーザー名)-p(パスワード)--default-character-set=utf 8データベース名>ローカルディスクへのバックアップ先
列子:mysqldump-h 192.168.1.10 -P3308 -uroot -proot --default-character-set=utf8 jiegouhua > C:\Users\Administrator\Desktop\sql\aa.sql
3、Java実現
主にJAVAのRunTimeクラスとProcessクラスを使用してコマンドウィンドウの操作を実現していますが、-p、-h、-u、-p(パスワード)と後の値の間にスペースを入れないでください.そうしないと予知できないエラーが発生します.
/**
	 * Java    MySQL     
	 * @param ip MySQL          IP
	 * @param host       
	 * @param userName             
	 * @param password            
	 * @param databaseName         
	 * @param savePath            
	 * @param fileName           
	 * @return   true      ,    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()) {//        
			saveFile.mkdirs();//      
		}
		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         。
				return true;
			}*/
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (printWriter != null) {
					printWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//return false;
	}