import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BackupMysql {
/** 访问MySQL数据库服务器所在的url */
private String serverUrl;
/** 访问MySQL数据库的用户名 */
private String username;
/** 访问MySQL数据库的密码 */
private String password;
public String getServerUrl() {
return serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public BackupMysql(String serverUrl,String username, String password) {
super();
this.serverUrl=serverUrl;
this.username = username;
this.password = password;
}
public String backup(String backupPath, String dbName) throws IOException {
String backupFile = backupPath+ dbName+ new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".sql";
String mysql = "mysqldump "+"--host="+serverUrl+" --user=" + username + " --password="+ password + " --opt " + dbName + "> " + backupFile;
java.lang.Runtime.getRuntime().exec("cmd /c " + mysql);
System.out.println("备份成功!");
return backupFile;
}
public void restore(String restoreFile, String dbName) throws Exception {
String mysql = "mysql "+"-h"+serverUrl+" -u" + username + " -p"+ password + " " + dbName + " < " + restoreFile;
System.out.println(mysql);
java.lang.Runtime.getRuntime().exec("cmd /c " + mysql);
System.out.println("还原成功!");
}
/**
* @param args
*/
public static void main(String[] args) {
String serverUrl="127.0.0.1";
String userName = "root";
String pwd = "root";
BackupMysql backup = new BackupMysql(serverUrl,userName, pwd);
try {
backup.restore("d:/nationz2010-12-20-14-16-47.sql", "nationz");
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过Java来备份与还原Mysql数据库的代码
最新推荐文章于 2024-11-01 11:00:05 发布
本文介绍了一个使用Java实现MySQL数据库备份和恢复的方法。通过命令行调用mysqldump工具进行备份,并通过mysql命令进行数据恢复。代码中包含了设置数据库连接信息、执行备份及恢复操作的完整流程。
摘要由CSDN通过智能技术生成