如何用Java实现MySQL数据库的备份和恢复

如何用Java实现MySQL数据库的备份和恢复,第1张

直接黏贴在IDEA上按格式查看

package com.liuzy.javaopen.servletimport java.io.BufferedReaderimport java.io.Fileimport java.io.FileInputStreamimport java.io.FileOutputStreamimport java.io.IOExceptionimport java.io.InputStreamimport java.io.InputStreamReaderimport java.io.OutputStreamimport java.io.OutputStreamWriterpublic 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 -pmysql goldenwing") 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 -pmysql --default-character-set=utf8 goldenwing") 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() }}

1 public static String comman="C:/Program Files/MySQL/MySQL Server 5.5/bin/mysql.exe -uroot -proot test"

2 public static void back(String mySqlBackupName,String mysqlBackupPath, String command){

3

4 String fPath=mysqlBackupPath+"/"+new Date().getTime()+".sql"

5

6 Runtime rt = Runtime.getRuntime()

7 try {

8 Process child = rt.exec(command)

9 InputStream in = child.getInputStream()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/sjk/9645252.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存