如何使用 Java 代码将我的 .sql 文件(包含 db dump )推送到服务器上的另一个数据库?

问题描述 投票:0回答:1
public class DumpFileClass{   

  public static boolean importDump(String host, String username, String password, String database, String dumpFilePath) {
           
            
            String mysqlCommand = "mysql -h " + host + " -u " + username + " -p" + password +" " + database + " < " + dumpFilePath;
            System.out.println(mysqlCommand);
            try {
                Process process = Runtime.getRuntime().exec(mysqlCommand);
                logger.trace(process);
                int exitCode = process.waitFor();
                logger.trace(exitCode);
                System.out.println(exitCode);

                return exitCode == 0;
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                return false;
            }
        }
 }
java process dump
1个回答
0
投票

您可以通过写入进程输入流来避免对 shell 的依赖。还要避免依赖于将数据库名称参数传递给

mysql
,因为这在恢复转储时通常不相关:

    public static boolean importDump(String host, String username, String password, 
            String dumpFilePath) {
        boolean result = false;
        String[] mysqlCommand = { "mysql",  "-h", host, "-u", username, "-p" + password };
        try {
            ProcessBuilder pb = new ProcessBuilder(mysqlCommand).redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT);
            Process process = pb.start();
            try (InputStream in = Files.newInputStream(Path.of(dumpFilePath));
                OutputStream out = process.getOutputStream()) {
                in.transferTo(out);
            }
            logger.trace(process);
            int exitCode = process.waitFor();
            logger.trace(exitCode);
            result = (exitCode == 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
© www.soinside.com 2019 - 2024. All rights reserved.