包 com.xxx.core.db; importjava.io。 * ;
公共 类 MySQLDatabaseBackup {
公共 静态 布尔 exportDatabase(字符串hostIP,字符串userName,字符串密码,字符串savePath,字符串fileName,字符串databaseName)throws InterruptedException {
文件saveFile = 新建 File(savePath);
如果(!saveFile.exists()){// 如果目录不存在
saveFile.mkdirs(); // 创建文件夹
}
如果(!savePath.endsWith(File.separator)){
savePath = savePath + File.separator;
}
PrintWriter printWriter = null ;
BufferedReader bufferedReader = null ;
试试
printWriter = 新建 PrintWriter(new OutputStreamWriter(新建 FileOutputStream(savePath + fileName)," utf8" )));
流程 = Runtime.getRuntime()。执行(" mysqldump-h" + hostIP +"-u" +用户名+"-p" +密码+"--set-charset = UTF8" + databaseName);
InputStreamReader inputStreamReader = 新建 InputStreamReader(process.getInputStream()," utf8" );
bufferedReader = 新 BufferedReader(inputStreamReader);
字符串行;
而((line = bufferedReader.readLine())!= null ){
printWriter.println(行);
}
printWriter.flush();
如果(process.waitFor()== 0){// 0表示线程正常终止。
返回 true ;
}
} catch (IOException e){
e.printStackTrace();
} 最终
试试
如果(bufferedReader!= null ){
bufferedReader.close();
}
如果(printWriter!= null ){
printWriter.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
返回 false ;
}
公共 静态 布尔 importDatabase(字符串hostIP,字符串hostPort,字符串userName,字符串密码,字符串importFilePath,字符串sqlFileName,字符串databaseName){
文件imporFile = 新建 File(importFilePath);
如果(!imporFile.exists()){
imporFile.mkdirs();
}
如果(!importFilePath.endsWith(File.separator)){
importFilePath = importFilePath + File.separator;
}
试试
// 创建数据库:mysqladmin-h 192.168.1.40-u root-proot create icqr
字符串createDB =" mysqladmin-h" + hostIP +"-u" +用户名+"-p" +密码+"创建" + databaseName;
Runtime.getRuntime()。执行(createDB);
// 写数据:mysql-h127.0.0.1-uroot-P3306-p测试D:\\\\ backupDatabase \\\\
流程= Runtime.getRuntime()。执行(" cmd/C" +" mysql-h" + hostIP +"-P" + hostPort +"-u" +用户名+"-p" +密码+"" +数据库名+" \ lt;" + importFilePath + sqlFileName);
如果(process.waitFor()== 0 ){
返回 true ;
}
} catch (IOException e){
e.printStackTrace();
} catch (InterruptedException e){
e.printStackTrace();
}
返回 false ;
}
public 静态 void main(字符串[] args){
布尔结果 = true ;
// result = importDatabase(" 127.0.0.1"," 3306","根","密码"," D:\\\\\\\\ backupDatabase"," 2014-10-14.sql"," databaseName");
尝试 {
结果 = exportDatabase(" 127.0.0.1"," root"," password"," D:\\\\\\\\ backupDatabase \\\\"," backup.sql"," databaseName" );
} catch (异常e){
e.printStackTrace();
}
如果 (结果){
System.out.println("数据库备份成功" );
} 其他
System.out.println("数据库备份失败!!" );
}
}
}