Pages

Java MySQL Backup Local

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 *
 * @author Cy.Co.Labs
 */
public class jdbc {

    private static Connection c;
    private static PreparedStatement pr;
    public static Connection c2;
    static String dbName = "", dbUser = "", dbPassword = "", dbHost = "";
    static String filename = "";
    static String fileURI = "";

    private static Connection conn() throws Exception {
        if (c == null) {
            Class.forName("com.mysql.jdbc.Driver");

            c = (Connection) DriverManager.getConnection("jdbc:mysql://" + dbHost + ":3306/" + dbName, dbUser, dbPassword);
        }
        return c;
    }

    public static void putdata(String mysql) throws Exception {
        conn().createStatement().executeUpdate(mysql);
    }

    public static ResultSet getdata(String mysql) throws Exception {
        pr = conn().prepareStatement(mysql);
        ResultSet rs = (ResultSet) pr.executeQuery();
        return rs;
    }

    public static void deletedata(String mysql) throws Exception {
        conn().createStatement().executeUpdate(mysql);
    }

    public static Connection getConnetcion() throws Exception {
        c2 = conn();
        return c2;
    }

    public static void putbatch(String[] batch) throws Exception {
        Statement statement = jdbc.conn().createStatement();
        for (String query : batch) {
            statement.addBatch(query);
        }
        statement.executeBatch();
    }

    public static void executebackup(String mode) throws Exception {
        try {
            //first, local backup will execute on any request
            filename = Util.getUtil().getCurrentTimeStamp().replace("/", "").replace(" ", "-").replace(":", "") + ".sql";
            fileURI = "./BackupFolderName\\" + filename;

            String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " -h" + dbHost + " --database " + dbName + " -r " + fileURI;

            /*NOTE: Executing the command here*/
            Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            //start to process online upload the last previously generated file
            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            if (processComplete == 0) {
                System.out.println("Backup Complete");             
            } else {
                System.out.println("Backup Failure");
            }
            System.out.println("" + filename);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

No comments:

Post a Comment