数据库文件导出的shell文件:#!/bin/bash
mysqldump -h{host} -u{userName} -p{password} --skip-lock-tables dbName tableName>db-entity.sqlmysql
数据库文件导入的shell文件:#!/bin/bash
mysql -h{host} -u{userName} -p{password} dbName <db-entity.sqlsql
注:host/userName/password 是Java调用shell时传递过来的参数shell
Java代码:数据库
HashMap<String,String> rkdMap = new HashMap<String, String>(); //将参数放入集合中
rkdMap.put("host", dbAddress);
rkdMap.put("userName", userName);
rkdMap.put("password", passWord);
String command = JSONUtil.getStringByParamMap(commandPath,rkdMap);bash
rt = ShellUtil.execCmd(command);app
/ * *
* execCmd()方法
* 执行系统命令, 返回执行结果
* @param cmd 须要执行的命令
*/
public static String execCmd(String cmd) {
StringBuilder result = new StringBuilder();ui
Process process = null;
BufferedReader bufrIn = null;
BufferedReader bufrError = null;spa
try {
String[] commond = {"/bin/sh","-c",cmd};
// 1. 执行命令, 返回一个子进程对象(命令在子进程中执行)
process = Runtime.getRuntime().exec(commond);.net
// 2. 方法阻塞, 等待命令执行完成(成功会返回0)
process.waitFor();对象
// 3. 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入)
bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
// 4. 读取输出
String line = null;
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
}
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
}
}catch (Exception e){
e.printStackTrace();
}finally {
closeStream(bufrIn);
closeStream(bufrError);
// 5.销毁子进程
if (process != null) {
process.destroy();
}
}
// 6. 返回执行结果 return result.toString(); }