如何在 java 代码中 运行 mysqldump 命令?

How to run mysqldump command in java code?

我想在我的函数中测试 运行 mysqldump 命令,但我无法创建 aaadumpdb.sql 文件。我的代码如下:

@Test
public void dumpDB() {
    Process p = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        p = runtime
                .exec("mysqldump -u root -padmin --add-drop-database aaa_db "
                        + "D:\backupdenemeaaa " + "aaadumpdb.sql");
        // change the dbpass and dbname with your dbpass and dbname
        int processComplete = p.waitFor();

        if (processComplete == 0) {

            System.out.println("Backup created successfully!");

        } else {
            JOptionPane.showMessageDialog(new JDialog(),
                    "Could not create the backup");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    File f = new File("aaadumpdb.sql");

    assertTrue(f.exists());
}

有人可以给我一些建议吗?谢谢。

我在我的代码中做了一些编辑,但是当我 运行 时,我的代码进入了 else 结构。可能是什么问题?

我编辑的代码如下:

    @Test
public void dumpDB() {
    Process p = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        String mysqldumpExecutable = "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe";
        p = runtime.exec(mysqldumpExecutable + " -uroot -padmin --add-drop-database -B aaa_db -r" + "D:\backupdenemeaaa " + "\aaadumpdb.sql");
        // change the dbpass and dbname with your dbpass and dbname
        int processComplete = p.waitFor();

        if (processComplete == 0) {

            System.out.println("Backup created successfully!");

        } else {
            JOptionPane.showMessageDialog(new JDialog(),
                    "Could not create the backup");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    File f = new File("aaadumpdb.sql");

    assertTrue(f.exists());

我该如何解决这个问题?谢谢。

添加以下代码片段以了解到底发生了什么

try
        {
            InputStreamReader isr = new InputStreamReader(process.getErrorStream());
            BufferedReader br = new BufferedReader(isr,4094);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(type + "> " + line);    
            } catch (IOException ioe)
              {
                ioe.printStackTrace();  
              }
    }

您将了解该流程执行中可能发生的异常和错误

堆栈跟踪确实有助于调试它,但我相信您可以检查 "mysqldump" 是否在您的 PATH 中,否则应用程序将简单地找不到可执行文件。如果你不想弄乱你的路径,你可以像下面这样硬编码可执行文件的路径:

String mysqldumpExecutable = "C:\apps\mysql\mysqldump.exe";
runtime.exec(mysqldumpExecutable + "-u root -padmin --add-drop-database aaa_db (.....));

当您说您无法创建文件时,这到底是什么意思?你有错误吗?什么都没发生?帮助我们帮助你。