日期:2014-05-16  浏览次数:20519 次

java代码实现备份MySQL数据库

?public static void backupMysqlDatabase(String mysqlBinUrl, String hostName,
???String dataBase, String userName, String passwd, String outFilePath)
???throws Exception {
??// 组装MySQL的备份命令
??StringBuilder sqlStr = new StringBuilder();
??sqlStr.append(mysqlBinUrl).append("mysqldump -u").append(userName)
????.append(" -p").append(passwd).append(" ").append(dataBase);
??if (hostName != null && !hostName.equals("")) {
???sqlStr.append(" ").append(" -h").append(hostName);
??}
??// --default-character-set=gb2312
??// 调用系统cmd 命令执行备份命令
??Runtime rt = Runtime.getRuntime();
??Process process = rt.exec(sqlStr.toString());
??InputStream in = process.getInputStream();// 控制台的输出信息作为输入流
??InputStreamReader isr = new InputStreamReader(in, "utf8");

??StringBuilder sb = new StringBuilder("");
??String inStr;
??// 组合控制台输出信息字符串
??BufferedReader br = new BufferedReader(isr);
??while ((inStr = br.readLine()) != null) {
???sb.append(inStr).append("\r\n");
??}

??// 把备份数据写入到文件中
??FileOutputStream fout = new FileOutputStream(outFilePath);
??OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
??writer.write(sb.toString());
??writer.flush();
??// 写完文件,关闭相应的流
??in.close();
??isr.close();
??br.close();
??writer.close();
??fout.close();
?}
??? public static void main(String[] args) {??
??????? // TODO Auto-generated method stub??
??? ?BackupDb? backupMysqlDb = new BackupDb ();??
??????? String hostName = "192.168.1.226";??
??????? String dataBase = "iae";//is??
??????? String userName = "iaeuser";??
??????? String passwd = "iaedata";??
??????? String outFilePath = "D:\\backupmysql.sql";
??????? String outFilePath1 = "E:\\backupmysql.sql";
??????? String mysqlBinUrl="C:/Program Files/MySQL/MySQL Server 5.1/bin/";
??????? try {??
???????? backupMysqlDb.backupMysqlDatabase(mysqlBinUrl,hostName,dataBase, userName, passwd, outFilePath1);??
??????? } catch (Exception e) {??
???????? // TODO Auto-generated catch block??
???????? e.printStackTrace();??
???????? System.out.println(" 备份MySQL失败");??
??????? }??
??????? System.out.println(" 备份MySQL 成功");??
????? }?