Note

Building SQL queries out of String literals is made easier in Java by a convenient mismatch between the two languages. In Java, Strings are delimited by double quotes 0 whereas in SQL literals are bounded by single quotes 0- Thus in Java, you can construct SQL queries that contain literal string references without much trouble, as in:

If this all seems rather simplistic, well, it is. It may not be a very sophisticated way of blending SQL with Java, but it is very effective. Notice that you don't get any syntax checking on the SQL query when you write your program, though it will throw an exception at runtime if you try to execute ungrammatical SQL. For this reason it is not uncommon to try out all your SQL beforehand, cutting and pasting the queries out of the SQL program that you use for directly talking with your database. Some developers even like to keep their queries in files, to be read at runtime. This has the added flexibility (and risk) of being able to change the query without recompiling the code. Since the recompile doesn't provide any syntax checking on your query string anyway, it seems a reasonable way to go, provided that you properly write-protect the files containing the queries.

Was this article helpful?

0 0

Post a comment