java 如何备份mysql
使用 Java 备份 MySQL 数据库
使用 mysqldump 命令行工具
Java 可以通过 Runtime.exec() 或 ProcessBuilder 调用系统的 mysqldump 工具来备份 MySQL 数据库。以下是示例代码:
import java.io.IOException;
public class MySQLBackup {
public static void backupDatabase(String host, String port, String user, String password, String database, String outputFile) throws IOException {
String command = String.format(
"mysqldump -h %s -P %s -u %s -p%s %s > %s",
host, port, user, password, database, outputFile
);
Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", command});
try {
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("Backup completed successfully");
} else {
System.err.println("Backup failed with exit code: " + exitCode);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
使用 JDBC 导出数据
通过 JDBC 连接数据库,手动导出数据到文件:
import java.io.FileWriter;
import java.sql.*;
public class JDBCBackup {
public static void exportToCSV(String jdbcUrl, String user, String password, String outputFile) {
try (Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
Statement stmt = conn.createStatement();
FileWriter writer = new FileWriter(outputFile)) {
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table");
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
writer.append(rs.getString(i));
if (i < columnCount) writer.append(",");
}
writer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用第三方库
Apache Commons 和 MySQL Connector 可以提供更便捷的备份方式:
import org.apache.commons.io.FileUtils;
import java.nio.charset.StandardCharsets;
import java.sql.*;
public class LibraryBackup {
public static void backupWithLib(String jdbcUrl, String user, String password, String outputFile) throws SQLException {
StringBuilder sb = new StringBuilder();
try (Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SHOW TABLES");
while (rs.next()) {
String table = rs.getString(1);
sb.append(String.format("-- Table: %s\n", table));
ResultSet tableData = stmt.executeQuery(String.format("SELECT * FROM %s", table));
// 处理数据...
}
FileUtils.writeStringToFile(new File(outputFile), sb.toString(), StandardCharsets.UTF_8);
}
}
}
定时备份实现
结合 Java 的定时任务功能实现定期备份:
import java.util.Timer;
import java.util.TimerTask;
public class ScheduledBackup {
public static void scheduleBackup(long periodInHours) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
MySQLBackup.backupDatabase("localhost", "3306", "root", "password", "mydb", "backup.sql");
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, periodInHours * 60 * 60 * 1000);
}
}
注意事项:

- 确保有足够的磁盘空间存储备份文件
- 备份敏感数据时需要考虑加密和安全存储
- 大型数据库备份可能需要较长时间,建议在低峰期进行
- 定期测试备份文件的恢复功能,确保备份有效






