用Java代碼備份和還原MySQL數據庫

xmnx 9年前發布 | 9K 次閱讀 Java

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(); } }

                </pre> 


 本文由用戶 xmnx 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!