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?

asked Jul 5, 2013 at 15:01
3
  • 3
    Just curious, why don't you use JDBC? Also, looks like AssetID is a varchar, and > operator does not make sense as it isn't really deterministic. What exactly is greater than 'G123204E4-1234-4A31-B37B-0092D68DA429'? Commented Jul 5, 2013 at 15:06
  • Try escaping the ">" by using "\>". Commented Jul 5, 2013 at 15:07
  • not working escaping the ">" by using "\>" Commented Jul 5, 2013 at 15:10

1 Answer 1

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"});
answered Jul 5, 2013 at 15:13
Sign up to request clarification or add additional context in comments.

1 Comment

` .exec("sqlcmd","-m-1", "-S","localhost,1433","-d",....)` BUT you are already in JAVA, just use JDBC

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.