Java写一个每晚12点定时备份达梦数据库数据的代码
时间: 2024-10-09 16:15:27 浏览: 47
oracle备份shell
在Java中,你可以使用`java.util.Timer`或更现代的`java.time`和`ScheduledExecutorService`来创建一个定时任务,结合JDBC(Java Database Connectivity)来执行数据库备份。以下是一个基本的示例,使用`ScheduledExecutorService`,因为它提供了更多的灵活性和控制。
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import javax.sql.DataSource;
public class BackupTask implements Runnable {
private static final String BACKUP_QUERY = "INSERT INTO backup_table SELECT * FROM main_table";
private DataSource dataSource;
public BackupTask(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run() {
try {
// 获取当前时间并转换为指定时区(例如UTC)
LocalDateTime currentDateTime = LocalDateTime.now().atZone(ZoneId.of("UTC"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm");
String backupFileName = "backup_" + currentDateTime.format(formatter) + ".sql";
// 连接到数据库
Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(BACKUP_QUERY);
// 执行备份查询
stmt.executeUpdate();
// 关闭连接
stmt.close();
conn.close();
System.out.println("Backup completed for time: " + backupFileName);
} catch (SQLException e) {
System.err.println("Error during backup: " + e.getMessage());
}
}
public static void main(String[] args) {
// 创建一个基于文件系统的数据源
// 注意替换实际的URL、用户名和密码
String url = "jdbc:dmdb://localhost:1521/mydatabase";
String username = "your_username";
String password = "your_password";
try {
DataSource dataSource = DriverManager.getConnection(url, username, password)..unwrap(DataSource.class);
// 使用ScheduledExecutorService来调度任务每晚12点执行
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new BackupTask(dataSource), 0, 1, TimeUnit.DAYS); // 每天午夜12点执行
executor.shutdown(); // 不关闭,否则会在第一次执行后立即停止
System.out.println("Backup task scheduled. Press Ctrl+C to stop.");
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
阅读全文