我如何从mysql数据库备份和恢复数据

2024-04-22

我想知道如何从 mysql 数据库创建备份并恢复它。 我想在我的java应用程序中使用它。

mysql> mysql -u root -p 123  -h hostname club <dumpfile.sql;

但它有这个错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root -p mehdi  -h hostname club < dumpfile.sql' at line 1   

import java.io.IOException;  
/**  
*  
* @author [email protected] /cdn-cgi/l/email-protection  
*/  

public class DatabaseManager {  

public static boolean backup(String mysqldumpPath, String backupPath) {
    boolean status = false;
    String username = "name";
    String password = "pword";
    String database = "database_name";


    String command = "/" + mysqldumpPath + "/mysqldump -u " + username + " -p" + password + " " + database + " -r " + backupPath;
    try {
        Process runtimeProcess = Runtime.getRuntime().exec(command);
        int processComplete = runtimeProcess.waitFor();
        if (processComplete == 0) {
            System.out.println("DatabaseManager.backup: Backup Successfull");
            status = true;
        } else {
            System.out.println("DatabaseManager.backup: Backup Failure!");
        }
    } catch (IOException ioe) {
        System.out.println("Exception IO");
        ioe.printStackTrace();
    } catch (Exception e) {
        System.out.println("Exception");
        e.printStackTrace();
    }
    return status;
}
public static boolean restore(String filePath){
    boolean status = false;
    String username = "name";
    String password = "pword";
    String[] command = new String[]{"mysql", "database_name", "-u" + username, "-p" + password, "-e", " source "+filePath };

    try {
        Process runtimeProcess = Runtime.getRuntime().exec(command);
        int processComplete = runtimeProcess.waitFor();
        if (processComplete == 0) {
            System.out.println("DatabaseManager.restore: Restore Successfull");
            status = true;
        } else {
            System.out.println("DatabaseManager.restore: Restore Failure!");
        }
    } catch (IOException ioe) {
        System.out.println("Exception IO");
        ioe.printStackTrace();
    } catch (Exception e) {
        System.out.println("Exception");
        e.printStackTrace();
    }
    return status;
}

//for testing
public static void main(String args[]){
    String backupName = "D:/DatabaseBackup/backupHvs.sql";
    DatabaseManager.restore(backupName);
}

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何从mysql数据库备份和恢复数据 的相关文章

随机推荐