如何在Java中执行SQL脚本文件? [英] How to Execute SQL Script File in Java?

查看:1317
本文介绍了如何在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.
    • 这篇关于如何在Java中执行SQL脚本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆