I am facing an error executing sqlcmd from Java. My code is below:
Process process = Runtime.getRuntime()
.exec("sqlcmd -m-1 -S localhost,1433 -d my_server -U sa
-P abc -Q \"select * from Assests where AssetID >
'G123204E4-1234-4A31-B37B-0092D68DA429'\" -k2 -W
-h-1 -s\",\" -o \"D://Assests.csv\"");
While running sqlcmd from sqlclient its working fine but from Java it is giving the following expression error:
Msg 4145, Level 15, State 1, Server SANDEEPB-PC, Line 1 An expression of non-boolean type specified in a context where a condition is expected, near 'AssetID'.
Yet, when I change ">" to "=", it works fine.
Can someone please tell me why this is happening and what I can do about it?
1 Answer 1
You should pass the command using the string array version of exec(), see: http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String[]) This will properly escape all the arguments.
See Java Runtime exec() fails to escape characters properly
It should look like this (not tested);
Process process = Runtime.getRuntime()
.exec(new String[] {"sqlcmd", "-m", "-1", "-S", "localhost,1433", "-d", "my_server", "-U", "sa", "-P", "abc", "-Q", "select * from Assests where AssetID > 'G123204E4-1234-4A31-B37B-0092D68DA429'", "-k2", "-W", "-h", "-1", "-s", ",\"", "-o", "D://Assests.csv"});
for MySQL (tested)
Process process = Runtime.getRuntime()
.exec(new String[] {"mysql", "-u", "root", "-ppassword","-e", "select 1<2"});
>operator does not make sense as it isn't really deterministic. What exactly is greater than'G123204E4-1234-4A31-B37B-0092D68DA429'?