0

I need to get the SQL commands from a .sql file using java.

The file contains lines with "--" at the start so ideally it would ignore these lines.

I have looked into using .useDelimiter("(;(\r)?\n)|(--\n)");

I need to use a while loop which reads the file and finds the SQL commands and executes them as it finds them. The examples I have looked at dont seem very efficent.

Any help on this would be much appreciated :)

  • 2
    This is a seemingly simple problem that can quickly spin out of control. SQL actually has a very complex grammar, allows statements to span multiple lines, comments. Very hard to deal with in a simple while-loop. Check out http://www.sqlparser.com/ for a more robust solution. – Matt Fenwick Nov 01 '11 at 16:33
  • Maybe this is an option? http://stackoverflow.com/q/2071682/395975 – smp7d Nov 01 '11 at 16:55

1 Answers1

2

Are you sure you really want this? It is much easier to run this script using DB specific command line utilities.

For example for MySql the command line is mysql -uUSER -pPASSWORD < a.sql It is simple, fast and works 100%. If you want to run it from java use Runtime.getRuntime().exec() or ProcessBuilder.

It is not a problem to read SQL file line-by-line and ignore comments (either using regular expression '^--' or line.startsWith("--"). It is a problem to find the beginning and the end of each SQL statement. Moreover you cannot run statements from script separately. SQL supports variables. One statement can define variable, other can use it. See also what @Matt Fenwick wrote.

AlexR
  • 114,158
  • 16
  • 130
  • 208