2

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?

Tim Post
  • 33,371
  • 15
  • 110
  • 174
sandybo
  • 73
  • 1
  • 10

1 Answers1

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"});
Community
  • 1
  • 1
Jasper Krijgsman
  • 1,018
  • 11
  • 13