如何在Java中执行SQL脚本文件?

问题描述:

我想用Java执行一个SQL脚本文件而不将整个文件内容读入大查询并执行它。

I want to execute an SQL script file in Java without reading the entire file content into a big query and executing it.

还有其他标准方法吗?

没有可移植的方法。您可以执行本机客户端作为外部程序来执行此操作:

There is no portable way of doing that. You can execute a native client as an external program to do that though:

import java.io.*;
public class CmdExec {

  public static void main(String argv[]) {
    try {
      String line;
      Process p = Runtime.getRuntime().exec
        ("psql -U username -d dbname -h serverhost -f scripfile.sql");
      BufferedReader input =
        new BufferedReader
          (new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();
    }
    catch (Exception err) {
      err.printStackTrace();
    }
  }
}




  • 代码示例是从此处中提取并修改为回答问题,假设用户需要执行PostgreSQL脚本文件。

    • Code sample was extracted from here and modified to answer question assuming that the user wants to execute a PostgreSQL script file.