import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MysqlBackupUtils {
private static final String url = "jdbc:mysql://localhost/test";
private static final String driver = "com.mysql.jdbc.Driver";
private static final String user = "root";
private static final String password = "123456";
private static final String host = "localhost";
private static final String database = "test";
/**获取操作系统类型**/
private static final String OS = System.getProperty("os.name").toLowerCase();
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
new RuntimeException(e);
}
}
public static void backup(String tableName, String path) throws IOException, InterruptedException, SQLException {
if (OS.indexOf("windows") >= 0) {
backupWindows(tableName, path);
}
}
private static void backupWindows(String tableName, String path) throws IOException, InterruptedException, SQLException {
//##上传之后的视频文件名为test.tmpmedia
String baseDir = getBaseDir();
String fileName = path + File.separator + tableName + new SimpleDateFormat("YYYYMMDDHHMMSS").format(new Date()) + ".sql";
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
String command = baseDir + File.separator + "bin/mysqldump.exe -h" + host + " -u" + user + " -p" + password + " " + database + " " + tableName + " --result-file=" + fileName;
//String command = "C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin\\mysqldump.exe -hlocalhost -uroot -p123456 test user --result-file=D:/user.sql";
Process p = Runtime.getRuntime().exec(command);
//##读取命令的输出信息
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
p.waitFor();
if (p.exitValue() != 0) {
//说明命令执行失败
//可以进入到错误处理步骤中
System.out.println(p.getErrorStream());
is = p.getErrorStream();
reader = new BufferedReader(new InputStreamReader(is));
}
StringBuffer sb = new StringBuffer(1024);
String outStr;
// 组合控制台输出信息字符串
while ((outStr = reader.readLine()) != null) {
sb.append(outStr).append("\r\n");
}
outStr = sb.toString();
System.out.println(outStr);
}
/**
* 获取数据库配置的根目录
* @return
* @throws SQLException
*/
private static String getBaseDir() throws SQLException {
Connection connection = DriverManager.getConnection(url, user, password);//获取连接
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select @@global.basedir");
String rt = null;
if (resultSet.next()) {
rt = resultSet.getString(1);
}
resultSet.close();
statement.close();
connection.close();
return rt;
}
public static void main(String[] args) throws IOException, InterruptedException, SQLException {
backup("sys_menu", "D:");
}
}