简体   繁体   English

使用Runtime.getRuntime()。exec()在运行时在Java中执行sql语句

[英]execute sql statements in java at runtime using Runtime.getRuntime().exec()

In the below code while loop is not running. 在下面的代码中,while循环未运行。 Can someone suggest me what is going wrong with this code. 有人可以建议我这段代码出了什么问题。

import java.io.*;

public class A 
{
    public static void main(String args[]) {
        int value = 0;
        String sql = "SELECT * FROM A2A_TP_INFO";
        String filename="file.txt";
        String filepath="/home/mit"+"export/file.txt";
        String exportQuery = "/home/mit/JavaProj/proj/export/query";
        String cmd[] = {
            "/bin/ksh",
            "-c",
            "" + exportQuery + " " +filepath+ "   \""
            + sql + ";\" " 
        };

        try {
            //Process p = Runtime.getRuntime().exec(cmd);
            Process p1=Runtime.getRuntime().exec(sql);
            // p.waitFor();
            BufferedReader input = new BufferedReader(new InputStreamReader(
                p1.getInputStream())); 

            while ((value = input.read()) != -1) {
                char c = (char) value;
                System.out.println(c);
            }
            input.close();
        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }
}

Don't use an intermediary shell. 不要使用中间外壳。 And use a ProcessBuilder : 并使用ProcessBuilder

final List<String> fullCommand = Arrays.asList(exportQuery, filePath, sql + ';')
final ProcessBuilder builder = new ProcessBuilder(fullCommand);
final Process p = builder.start();

Note that using ProcessBuilder you can send stdout/stderr to a file, and even customize stdin. 请注意,使用ProcessBuilder可以将stdout / stderr发送到文件,甚至可以自定义stdin。 You can set the working directory, customize the environment etc. Use that. 您可以设置工作目录,自定义环境等。 Really. 真。 Runtime.exec() has no reason to be used anymore. Runtime.exec()没有理由再使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM