备份数据库指令:
mysqldump -h127.0.0.1 -uroot -p123456 test > d:/test.sql ---备份test数据库到 D 盘
恢复数据库指令
mysql -h127.0.0.1 -uroot -p123456 test< test.sql ---将D备份的数据库脚本,恢复到数据库中(数据库要存在!)
在 cmd
或者 shell
调用命令行,其实是调用 MySQL
安装路径下面的 bin
目录下面的 msqldump.exe
和 mysql.exe
来完成相应的工作。
下面是使用 Java
代码实现在 Linux
端调用指令:
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DbOperate {
public static void dbBackUp(String root, String pwd, String dbName, String backPath, String backName) throws Exception {
String pathSql = backPath + backName;
File fileSql = new File(pathSql);
if (!fileSql.exists()){
fileSql.createNewFile();
}
StringBuffer sb = new StringBuffer();
sb.append("mysqldump");
sb.append(" -h127.0.0.1");
sb.append(" -P3306");
sb.append(" -u" + root);
sb.append(" -p" + pwd);
sb.append(" " + dbName + ">");
sb.append(pathSql);
System.out.println("cmd命令为:" + sb.toString());
Runtime runtime = Runtime.getRuntime();
System.out.println("开始备份:" + dbName);
String[] command = {"/bin/sh", "-c", sb.toString()};
// Process process = runtime.exec("/bin/sh -c " + sb.toString());
Process process = runtime.exec(command);
System.out.println(process.waitFor());
System.out.println("备份成功!!!!!");
}
public static void dbRestore(String root, String pwd, String dbName, String filePath){
StringBuffer sb = new StringBuffer();
sb.append("mysql");
sb.append(" -h127.0.0.1");
sb.append(" -P3306");
sb.append(" -u" + root);
sb.append(" -p" + pwd);
sb.append(" " + dbName + "<");
sb.append(filePath);
System.out.println("cmd命令为:" + sb.toString());
Runtime runtime = Runtime.getRuntime();
System.out.println("开始恢复:" + dbName);
try {
String[] command = {"/bin/sh", "-c", sb.toString()};
Process process = runtime.exec(command);
//Process process = runtime.exec("/bin/sh -c " + sb.toString());
InputStream is = process.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "utf8"));
String line = null;
while ((line = bf.readLine()) != null){
System.out.println(line);
}
is.close();
bf.close();
}catch (IOException e){
e.printStackTrace();
}
System.out.println("还原成功!!!!!");
}
public static void main(String[] args) throws Exception {
String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".sql";
//DbOperate.dbBackUp("root", "root", "db_other", "/hadoop/", backName);
DbOperate.dbRestore("root", "root", "db_sssss", "/hadoop/2021-11-30-11-41-25.sql");
}
}
经过测试,必须将 command
放到一个数组里面,才能将指令执行成功
linux下:
String[] command = { "/bin/sh", "-c", command };
Process ps = Runtime.getRuntime().exec(command );
windows下:
String[] command = { "cmd", "/c", command};
Process ps = Runtime.getRuntime().exec(command );