views:

104

answers:

6

I'm writing this in JAVA :

stmt.executeQuery("SELECT * FROM mytable INTO OUTFILE '/tmp/mytable.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' ;");

This is has to be written between " " as show because It has to be a String. However, when I run the code it says "Unclosed String and Character laterals". I know, but how to not let the compiler be confused by the " and ' which are part of the inner statement ? I want the compiler to consider them normal Strings not Java operations.

Plz Help!

+6  A: 

Escape them with a backslash: " Hello \"world\"!"

I'm not sure if it will help in this particular case, but try a PreparedStatement: it often allows you to not have to worry about quoting of arguments. (I haven't seen it used for this sort of non-CRUD SQL, so I'm not sure it will help).

Mark Peters
I think there's also a problem with double unescaping of `'\\'` and possibly `'\n'`. Should probably be `'\\\\'` and `'\\n'`.
Tom Hawtin - tackline
+1 for the prepared statement - I would also recommend using bind variables - less problems with potential security holes that way.
aperkins
A: 

You will need to also double the backslashes, f.e you will need to write \n.

Tassos Bassoukos
A: 

Use \" characters to put " in your string.

Riduidel
A: 

You need to escape the inside string with \:

"Bob said \"hello world\" to his friends learning Java."

Also, the backslashes in your string need to be escaped too:

"This is a backslash: \\, so two backslashes would be \\\\"

When in doubt, add more backslashes.

orangeoctopus
+4  A: 

In Java, strings are denoted with double quotations, so you shouldn't need to worry about the single quotations in your string. However, you need to escape the double quotations in your query by escaping them with a backslash \.

This should be correct: stmt.executeQuery("SELECT * FROM mytable INTO OUTFILE '/tmp/mytable.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n' ;");

Edit: You also needed to escape the existing backslashes in your query. The above line should work.

danyim
+1  A: 

Look at Escape Sequences:

http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/data/characters.html

Your final string will look like this:

"SELECT * FROM mytable INTO OUTFILE '/tmp/mytable.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\' LINES TERMINATED BY '\n' ;"

Also, realizes that "\\" will produce a \ so if you really want two slashes, you'll need "\\\\", and if you want it to print out \n, you need to type "\\n" etc.

Grantismo