DEVFYI - Developer Resource - FYI

What is the JDBC syntax for using a literal or variable in a standard Statement?

JDBC Interview Questions and Answers


(Continued from previous question...)

What is the JDBC syntax for using a literal or variable in a standard Statement?

First, it should be pointed out that PreparedStatement handles many issues for the developer and normally should be preferred over a standard Statement.
Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often affects newbies ( and others ) is that SQL, like many languages, requires quotes around character ( read "String" for Java ) values to distinguish from numerics. So the clause:
"WHERE myCol = " + myVal
is perfectly valid and works for numerics, but will fail when myVal is a String. Instead use:
"WHERE myCol = '" + myVal + "'"
if myVal equals "stringValue", the clause works out to:
WHERE myCol = 'stringValue'
You can still encounter problems when quotes are embedded in the value, which, again, a PreparedStatement will handle for you.

(Continued on next question...)

Other Interview Questions