简体   繁体   中英

Running sql queries from JDBC

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 ?

I would replace

sb.append(line);

with

sb.append(" ").append(line);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM