web-dev-qa-db-fra.com

Sauvegarde et restauration simples pour la base de données mysql de Java

Comment sauvegarder une base de données mysql à partir d'un code Java tel que:

  1. Son chemin d'enregistrement est alloué dynamiquement.
  2. Les espaces dans Path ne créent pas de problèmes.
  3. Le chemin est généré à l'aide du fichier jar d'exécution.
  4. DBname, DBusername ou DBpass sont attribués dynamiquement.
  5. Création d'un dossier spécialisé pour enregistrer le fichier de sauvegarde.
16
chettyharish

Remarque: Les codes donnés ci-dessous sont un moyen de résoudre le problème et probablement pas la meilleure méthode. Tout est modifiable à l'intérieur du code. Si vous n'avez pas mysql dans les variables d'environnement, ajoutez le chemin avant mysqldump et mysql (par exemple Pour XAMPP, C:\xampp\mysql\bin\mysqldump)

(J'espère que cela résoudra vos problèmes. Il m'a fallu une journée pour tout comprendre et les mettre en œuvre correctement)

Méthode de sauvegarde:

public static void Backupdbtosql() {
    try {

        /*NOTE: Getting path to the Jar file being executed*/
        /*NOTE: YourImplementingClass-> replace with the class executing the code*/
        CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
        File jarFile = new File(codeSource.getLocation().toURI().getPath());
        String jarDir = jarFile.getParentFile().getPath();


        /*NOTE: Creating Database Constraints*/
        String dbName = "YourDBName";
        String dbUser = "YourUserName";
        String dbPass = "YourUserPassword";

        /*NOTE: Creating Path Constraints for folder saving*/
        /*NOTE: Here the backup folder is created for saving inside it*/
        String folderPath = jarDir + "\\backup";

        /*NOTE: Creating Folder if it does not exist*/
        File f1 = new File(folderPath);
        f1.mkdir();

        /*NOTE: Creating Path Constraints for backup saving*/
        /*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
         String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";

        /*NOTE: Used to create a cmd command*/
        String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;

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

        /*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");
        }

    } catch (URISyntaxException | IOException | InterruptedException ex) {
        JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
    }
}

Méthode de restauration:

public static void Restoredbfromsql(String s) {
        try {
            /*NOTE: String s is the mysql file name including the .sql in its name*/
            /*NOTE: Getting path to the Jar file being executed*/
            /*NOTE: YourImplementingClass-> replace with the class executing the code*/
            CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
            File jarFile = new File(codeSource.getLocation().toURI().getPath());
            String jarDir = jarFile.getParentFile().getPath();

            /*NOTE: Creating Database Constraints*/
             String dbName = "YourDBName";
             String dbUser = "YourUserName";
             String dbPass = "YourUserPassword";

            /*NOTE: Creating Path Constraints for restoring*/
            String restorePath = jarDir + "\\backup" + "\\" + s;

            /*NOTE: Used to create a cmd command*/
            /*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/
            String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            if (processComplete == 0) {
                JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s);
            } else {
                JOptionPane.showMessageDialog(null, "Error at restoring");
            }


        } catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) {
            JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage());
        }

    }
28
chettyharish

Si Hibernate est configuré correctement, c'est du gâteau:

Session session = HibernateUtil.getSessionFactory().openSession();
// for every table, have the bean implement Serializable and use the next 4 lines
List <TblBean> tblCollection = session.createCriteria(TblBean.class).list();
FileOutputStream backup = new FileOutputStream("backupOf"+TblBean.getClass().getName()+".dat");
ObjectOutputStream backupWriter = new ObjectOutputStream(backup);
backupWriter.write(tblCollection);
5
hd1
public static String getData(String Host, String port, String user, String password, String db,String table) throws Exception {

    //an "C:/xampp/mysql/bin/mysqldump" ---- location ito han mysqldump

    Process run = Runtime.getRuntime().exec(
            "C:/xampp/mysql/bin/mysqldump --Host="  + Host + " --port=" + port + 
            " --user=" + user + " --password=" + password +
            " --compact --databases --add-drop-table --complete-insert --extended-insert " +
            "--skip-comments --skip-triggers "+ db+" --tables "+table);

    InputStream in = run.getInputStream(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    StringBuffer temp = new StringBuffer();
    int count;
    char[] cbuf = new char[BUFFER];

    while ((count = br.read(cbuf, 0, BUFFER)) != -1)
        temp.append(cbuf, 0, count);

    br.close();
    in.close();

    return temp.toString();
}
2
asdf