Re: JDBC, PreparedStatement and named parameters
On 7/20/12 2:39 AM, Andreas Leitgeb wrote:
I'm rather new to JDBC, and somewhat experienced with
database access in other languages, like with ProC or
with the sqlplus-shell.
While in C/C++ eSql with ProC (not sure about correct
nomenclature) I can use named variables for the parameters,
jdbc seems like it would only allow positional parameters.
With Google, I stumbled over this approach:
http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html
which boils down to pre-processing the sql-statement, replacing
the named variables by "?" while creating an array of the parameters
such, that e.g. a snippet like this:
"... :a :c :b :a ..." and setting a -> x1, b -> x2, c -> x3
would turn into
"... ? ? ? ? ..." with an parameter array of { x1, x3, x2, x1 }
That almost looks like what I was hoping for, but when I see
that the article is 5 years old, then I'd hope that something
similar might meanwhile have been turned into a standard...
Does anyone here know of a way to use either named variables,
or at least something like these "foo {1} bar {0}" things
used in jsf4j and java.text.MessageFormat?
Depending on your needs, a JPA provider (such as Hibernate) may be a
better approach. It moves you away from low-level SQL, and into more
object oriented notation.
It isn't always the best solution, and my experience with Hibernate has
been mixed. It's worth looking into and learning about it. They tend
to be useful if you do exactly what they were designed for, and then
they get in your way when you need to do something different.