How to restore a MySQL database backup using Java

前端 未结 8 2138
日久生厌
日久生厌 2020-12-10 22:57

I was able to create a backup of my current mysql database as .SQL file using the mysqldump.exe with the help of the following java code. <

相关标签:
8条回答
  • 2020-12-10 23:42

    You should try DbUnit for backup and restore of database.Here is the demo code for that:

        try {
            Class.forName(DBDRIVER);
            Connection jdbcConnection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);
            IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
            connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
                        new MySqlDataTypeFactory());
    
             //////// Database backup
            ITableFilter filter = new DatabaseSequenceFilter(connection);
            IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
    
            ExcludeTableFilter excludeFilter = new ExcludeTableFilter();
            excludeFilter.excludeTable("DATABASECHANGELOG*");
            IDataSet excludedataset = new FilteredDataSet(excludeFilter, dataset);
            FlatXmlDataSet.write(excludedataset, new FileOutputStream(backupfilename));
    
            System.out.println("\n Complete backup successful.");
             //////// Database backup
    
    
             //////// Database restore
            IDataSetProducer producer = new FlatXmlProducer(new InputSource(restoreFileName));
            IDataSet dataSet = new StreamingDataSet(producer);
    
            TransactionOperation operation = new TransactionOperation(DatabaseOperation.INSERT);
            operation.execute(connection, dataSet);
             //////// Database restore
        } catch (DatabaseUnitException e) {
            e.printStackTrace();
            flag = false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-10 23:43
    public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {  
    String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source};  
    Process runtimeProcess;  
    try {  
    runtimeProcess = Runtime.getRuntime().exec(executeCmd);  
    int processComplete = runtimeProcess.waitFor();  
    if (processComplete == 0) {  
        System.out.println("Backup restored successfully");  
        return true;  
    }  
    } else {  
         System.out.println("Could not restore the backup");  
           }  
            } catch (Exception ex) {  
                ex.printStackTrace();  
            }  
            return false;  
    }  
    

    source example : "E:\\My Backup\\Test\\file.sql"

    0 讨论(0)
提交回复
热议问题