2018年6月29日14:00:48
閱讀數:1534
今天整了整整一整天,終于使用Java線上備份和還原MySQL資料庫了,哎,備份倒是很快,就是在還原的時候遇到了一個問題,也不報錯,結果将sql語句放到cmd中一運作才知道是編碼的問題,下面代碼。
首先将将Mysql的環境變量配上:你的mysql安裝目錄\bin;,放到系統變量中path變量中,最好是開始Mysql的遠端連接配接的功能,将mysql資料庫中的user表中的你連接配接mysql的使用者的host字段設定為%号。
- package com.hancai.base.admin.action;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- public class Test {
- public static void main(String[] args) throws IOException{
- backup("d:\\d.sql");
- recover("d:\\d.sql");
- }
- public static void backup(String path) throws IOException{
- Runtime runtime = Runtime.getRuntime();
- //-u後面是使用者名,-p是密碼-p後面最好不要有空格,-family是資料庫的名字
- Process process = runtime.exec("mysqldump -u root -p123456 family");
- InputStream inputStream = process.getInputStream();//得到輸入流,寫成.sql檔案
- InputStreamReader reader = new InputStreamReader(inputStream);
- BufferedReader br = new BufferedReader(reader);
- String s = null;
- StringBuffer sb = new StringBuffer();
- while((s = br.readLine()) != null){
- sb.append(s+"\r\n");
- }
- s = sb.toString();
- System.out.println(s);
- File file = new File(path);
- file.getParentFile().mkdirs();
- FileOutputStream fileOutputStream = new FileOutputStream(file);
- fileOutputStream.write(s.getBytes());
- fileOutputStream.close();
- br.close();
- reader.close();
- inputStream.close();
- }
- public static void recover(String path) throws IOException{
- Runtime runtime = Runtime.getRuntime();
- //-u後面是使用者名,-p是密碼-p後面最好不要有空格,-family是資料庫的名字,--default-character-set=utf8,這句話一定的加
- //我就是因為這句話沒加導緻程式運作成功,但是資料庫裡面的内容還是以前的内容,最好寫上完成的sql放到cmd中一運作才知道報錯了
- //錯誤資訊:
- //mysql: Character set \'utf-8\' is not a compiled character set and is not specified in the \'
- //C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\Index.xml\' file ERROR 2019 (HY000): Can\'t
- // initialize character set utf-8 (path: C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\),
- //又是讨人厭的編碼問題,在恢複的時候設定一下預設的編碼就可以了。
- Process process = runtime.exec("mysql -u root -p123456 --default-character-set=utf8 family");
- OutputStream outputStream = process.getOutputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
- String str = null;
- StringBuffer sb = new StringBuffer();
- while((str = br.readLine()) != null){
- sb.append(str+"\r\n");
- }
- str = sb.toString();
- System.out.println(str);
- OutputStreamWriter writer = new OutputStreamWriter(outputStream,"utf-8");
- writer.write(str);
- writer.flush();
- outputStream.close();
- br.close();
- writer.close();
- }
- }
下載下傳位址:Java線上備份和還原MySQL資料庫
轉載請注明出處,謝謝!