通过JAVA代码备份数据库数据

操作系统:Linux     数据库:MySQL

注意:只可用于备份代码运行环境下的数据库,例如A服务器运行代码,访问B服务器数据库进行备份,则不可行。

代码如下:

package com.remoteservice.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

/**
 * Created by jlm on 2019-12-03 14:07
 */
@RestController
@RequestMapping("/back")
public class TestController {

    @RequestMapping("up")
    public void backup(){
        try {
            if (exportDatabaseTool("服务器IP", "mysql登录账户", "登录密码!", "保存的路径", "保存文件(注意以.sql文件)", "数据库名称")) {
                System.out.println("数据库成功备份!!!");
            } else {
                System.out.println("数据库备份失败!!!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            //备份指定表
//            Process process = Runtime.getRuntime().exec("mysqldump remoteservice -h" + hostIP + " -u" + userName + " -p" + password +" --set-charset=UTF8 " + "--tables t_area");
            //备份整个库
            Process process = Runtime.getRuntime().exec("mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);
            //备份除xxx表以外
//            Process process = Runtime.getRuntime().exec("mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + "--ignore-table=" + databaseName + ".t_area " + databaseName);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
                printWriter.flush();
            }
            if (process.waitFor() == 0) {//0 表示线程正常终止。
                return true;
            }
            System.out.println("code" + process.waitFor());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}

以上代码亲测可用,好用记得点赞哦~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java 增量备份数据库可以通过以下步骤实现: 1. 首先需要连接到数据库,可以使用 JDBC API 连接到数据库。 2. 查询数据库中最后备份的时间戳,可以将时间戳保存在文件中或者从数据库中读取。 3. 执行增量备份,可以使用 SQL 语句查询指定时间戳之后的数据。 4. 将增量备份数据保存到文件中,可以使用 Java I/O API 保存到文件中。 下面是一个简单的 Java 代码示例: ```java import java.sql.*; import java.io.*; public class DatabaseBackup { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/DB_NAME"; String user = "USERNAME"; String password = "PASSWORD"; String filename = "backup.sql"; String timestampFile = "timestamp.txt"; try { // Connect to database Connection conn = DriverManager.getConnection(url, user, password); // Read last backup timestamp from file String lastTimestamp = ""; File file = new File(timestampFile); if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(file)); lastTimestamp = reader.readLine(); reader.close(); } // Backup database Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM table WHERE timestamp > '" + lastTimestamp + "'"); PrintWriter writer = new PrintWriter(new FileWriter(filename)); while (rs.next()) { writer.println(rs.getString("column1") + "," + rs.getString("column2") + "," + rs.getString("column3")); } writer.close(); // Save new backup timestamp to file writer = new PrintWriter(new FileWriter(timestampFile)); writer.println(System.currentTimeMillis()); writer.close(); // Close database connection conn.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用了 JDBC API 连接到数据库,读取了最后备份的时间戳,并执行了增量备份。增量备份数据保存到了文件中,新的备份时间戳也保存到了文件中。注意,这只是一个简单的示例,实际应用需要更加完善和健壮。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值