使用java备份Mysql数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21774894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:35:20  来源:igfitidea点击:

Mysql database backup by using java

javamysqlmysqldump

提问by user3214269

I am going to take database backup by using java code.This code is excuting fine but I am getting int processComplete = runtimeProcess.waitFor();This method calling is returning the integer as 1. So finally I am getting the message as could not create backup as sop.

我将使用 java 代码进行数据库备份。这段代码运行良好,但我得到 int processComplete = runtimeProcess.waitFor(); 此方法调用将整数返回为 1。所以最后我收到消息,因为无法创建备份作为 sop。

public static void main(String[] args) {

        String path = "D:/databasebackup/databasbac.sql";
        String username = "root";
        String password = "";
        String dbname = "rac";
        String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + username + " -p" + password + " --add-drop-database -B " + dbname + " -r " + path;
        Process runtimeProcess;
        try {
//            System.out.println(executeCmd);//this out put works in mysql shell
            runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
            System.out.println(executeCmd);
//            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();
            System.out.println("processComplete"+processComplete);
            if (processComplete == 0) {
                System.out.println("Backup created successfully");

            } else {
                System.out.println("Could not create the backup");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

回答by Manuel Spigolon

Try this:

尝试这个:

int processComplete = runtimeProcess.exitValue();

runtime info

运行时信息

Hope this helps

希望这可以帮助

回答by sumith madhushan

Try out my code for backup the database using java. It works well for me.

试试我的代码来使用 java 备份数据库。这对我来说很有用。

try {

     String filename = null;

     FileChooser.setVisible(true);

     int result = FileChooser.showSaveDialog(null);

     if (result == JFileChooser.APPROVE_OPTION) {
            filename = FileChooser.getSelectedFile().toString().concat(".sql");

            File file = new File(filename);

            if (file.exists()) {
                    Object option[] = {"Sim", "Nao"};

                    int opcao = JOptionPane.showOptionDialog(null, "aaa", "bbbb", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, option, option[0]);

                    if (opcao == JOptionPane.YES_OPTION) {
                             Runtime backup = Runtime.getRuntime();
                             backup.exec("C:\wamp\bin\mysql\mysql5.6.17\bin\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABSE NAME");
                             JOptionPane.showMessageDialog(null, "Backup succesfully");
                    } else {
                         FileChooserActionPerformed(evt);
                    }
           } else {
                 Runtime backup = Runtime.getRuntime();
                 backup.exec("C:\wamp\bin\mysql\mysql5.6.17\bin\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABASE NAME");
                 JOptionPane.showMessageDialog(null, "Backup succesfully");
           }
        }
    } catch (Exception e) {
          JOptionPane.showMessageDialog(null, e, "Error.!", 2);
}

And this is the DbOperation class That i have written.

这是我编写的 DbOperation 类。

import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbOperation {
       String url = "jdbc:mysql://localhost:3306/give your database name";
       String username = "your username";
       String password = "your password";
       Connection con = null;
       PreparedStatement pst = null;
       ResultSet rs = null;

       public Connection backupDB(){
              try{
                  con=DriverManager.getConnection(url, username, password);
              }catch(SQLException e){
                  System.out.println(e.getMessage());
              }
       return con;
      }
}

回答by Prateek Mishra

I was facing similar problem in database backup from MYSQL through JDBC. So I ran the below code.

我在通过 JDBC 从 MYSQL 备份数据库时遇到了类似的问题。所以我运行了下面的代码。

String path = C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump

String command= "cmd.exe /c "
                    + "\"\""+path+"\"  "
                    + " --user="+UserInputs.getDbUserName()
                    + " --password="+UserInputs.getDbPassword()
                    + " --host="+UserInputs.getDbConnectionIP()
                    + " --protocol=tcp "
                    + " --port="+UserInputs.getDbConnectionPort()
                    + " --default-character-set=utf8 "
                    + " --single-transaction=TRUE "
                    + " --routines "
                    + " --events "
                    + "\""+UserInputs.getDbName()
                    +"\" "
                    + ">"
                    + " \""
                    + "D:\MY DATA\DB_Backup.sql"
                    + "\""
                    + " \"";

Runtime runtime = Runtime.getRuntime(command);

In case password is blank remove the --password line. This will create your database backup.

如果密码为空,请删除 --password 行。这将创建您的数据库备份。

In case you are running this on LINUX replace

如果您在 LINUX 上运行它,请替换

cmd.exe /c

by

经过

/bin/sh -c

Thanks!

谢谢!