GPX
GPX

Reputation: 3645

Reading output file of SQLCMD using Java

I am executing a bunch of SQL scripts and trying to read the output log file, looking for errors, after each file is executed.

Here's how I execute the script.

String strCommand = "sqlcmd -S SERVERNAME -d DBNAME -U USERNAME -P PASSWORD -r0 -i \"SCRIPT.sql\" 2> \"OUTPUT.LOG\" 1> NULL";
Process process = Runtime.getRuntime().exec(strCommand);
process.waitFor();

I've redirected the standard output to NULL and errors to the log file. Immediately following the execution of the above statements, I try to read the contents of the OUTPUT.LOG file, using File Reader and BufferedReader. An exception is thrown when trying to open the OUTPUT.LOG file.

(The system cannot find the file specified)

I check the path where the file should be saved, and needless to say, it isn't there. When I try to manually execute the command via Command Prompt, it works and writes the log file with errors, as expected. What am I doing wrong?

Upvotes: 0

Views: 1504

Answers (1)

Matthew Farwell
Matthew Farwell

Reputation: 61705

Your redirections (the 2> etc) will work if you are running from a command shell, but not if you run directly from java like this.

Try the following (for Windows):

String strCommand = "cmd /c sqlcmd -S SERVERNAME -d DBNAME -U USERNAME -P PASSWORD -r0 -i \"SCRIPT.sql\" 2> \"OUTPUT.LOG\" 1> NULL";
Process process = Runtime.getRuntime().exec(strCommand);
process.waitFor();

Note the addition of cmd /c, which will run the string in a command shell.

Upvotes: 2

Related Questions