0

My requirement says to read the select sql query (a huge one around 300 lines) from a .txt file and run it through JDBC. I tried doing so and was successful in it as well for some, however now I have started getting a lot of trouble out of it.

While reading the file and running it from JDBC, I constantly gets error which says FROM keyword is not found, SQL comand not ended properly, sql exceptions.

In the code side, I am reading a .txt file and appending it into a stringbuffer like below : queryFile=new File("file location");

BufferedReader buffer=new BufferedReader(new FileReader(queryFile));


StringBuilder sb = new StringBuilder();
String line;
while((line=buffer.readLine()) !=null){

    sb.append(line);
}
sql=sb.toString();
System.out.println(sql);

When I print the sql statement in string builder and compare it with original query, it seems like spaces are missing which is why it could not recognise FROM keyword, Order by Keyword and other keywords.

Is there any other way that I can do it from which I would not get such issues ?

2
  • can you pls put here some lines of your txt file ?. remember, lines are ending with '\n'. isn't mistake there ? Commented Apr 2, 2018 at 9:53
  • 2
    You're stripping the terminating newline on read, but not appending it to your StringBuilder. Add sb.append('\n') after you append the line. Commented Apr 2, 2018 at 10:07

2 Answers 2

1

I would replace

sb.append(line);

with

sb.append(" ").append(line);
Sign up to request clarification or add additional context in comments.

1 Comment

This will also do. Thanks for the answer.
0

Got the answer. The thing which is missing in the above code is sb.append('\n'). I was not appending the new line char in my code which is why formatting was not up to the mark.

Correct code should be :

BufferedReader buffer=new BufferedReader(new FileReader(queryFile));

     StringBuilder sb = new StringBuilder();
                    String line;
                    while((line=buffer.readLine()) !=null){

                        sb.append(line);
sb.append('\n')
                    }
                    sql=sb.toString();
                    System.out.println(sql);

Comments

Your Answer

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.