Skip to content
Advertisement

How to read sql query from a txt-file in Java

I am having some some class that is sending queries to data base. Everything was working fine when the query was in the code, but as it’s pretty big, I decided to put it in a file and to read it with buffered reader, but it’s not working, I always get this:

java.sql.SQLException: ORA-00900: invalid SQL statement

Here is my query:

Here is the code I am using:

Advertisement

Answer

You only need to escape your double-quotes in Java string literals. If you’re reading the SQL query from a file, Java will have no problem with the double-quotes unescaped in the file.

Take out all the escapes on the double-quotes in your file, and it should work fine.

Also, create your StringBuilder before your while loop, so you you don’t start over each time, and that you don’t read two lines per iteration:

Additionally, instead of replacing the single-quotes at the end for the session ID value (which would work), use a ? JDBC placeholder, and use a PreparedStatement to bind the session ID before you execute the query. That would prevent possible SQL injection attempts, e.g. if sessionID was the string:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement