0

I am writing a program that can either accepts a ".sql" file or accepts an SQL statement from the stdin. The problem comes form stdin:

Scanner scanner = new Scanner(new BufferedInputStream( System.in));
System.out.println("Enter SQL statements");
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext()) {
    stringBuilder = stringBuilder.append(scanner.nextLine()).append("\n");
}
sqlQuery=stringBuilder.toString();

It is modified from the answer here. But when I enter or paste the statement(s) into the terminal, it does not go to the next step, instead the statement keeps appending "\n". I want the user input to end after they hit enter (similar to this problem but in Java). How do I do it?

Community
  • 1
  • 1
Dylan Czenski
  • 1,305
  • 4
  • 29
  • 49

2 Answers2

1

The code you present anticipates that the input will be terminated by the end of the stream with which the Scanner is associated, not by the end of a single line -- see how the scanner.nextLine() invocation is inside a while loop?

If you want to read only one line then get rid of the loop. Moreover, if you're not concatenating multiple lines, then you don't need a StringBuilder either. Be sure that this is what you want, however, for it is relatively common for SQL statements to be written in multiline format.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Note: text-mode SQL interfaces commonly accept multiline input. They generally look for some sort of delimiter to recognize the end of a query, such as a period or semicolon on a line by itself. – John Bollinger Mar 15 '17 at 20:19
  • But some sql statements consist of multiple commands, such as multi-table insertion or creating a view and then extracting data from it – Dylan Czenski Mar 15 '17 at 20:23
  • @DylanChensky, multiple commands are not an issue, as you can just enter them sequentially. Multiline *individual* commands are a different matter, and if you want to support these then you have a fundamental problem: how is the program supposed to recognize a given line as the last in a command, vs. expecting additional lines to follow? I already said a word or two about that in my previous comment. – John Bollinger Mar 15 '17 at 20:35
1

To collect all the input until a double new-line (a blank line), you can set a custom delimiter on the Scanner, using a regex, and it will collect the input with a single call to scanner.next().

Scanner scanner = new Scanner(System.in);

System.out.println("Enter SQL statements");

scanner.useDelimiter("\n\n"); // an empty line
String sqlQuery = scanner.next();
scanner.reset(); // resets the delimiter
4castle
  • 32,613
  • 11
  • 69
  • 106