Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a Column name as Input Parameter of a PreparedStatement

I already used the search here (and other forums as well) but haven't found an answer exacty to what I'm trying to do.

I know that it can easily be done in some other way, and this is just a small sandbox-framework I'm coding for a University course... in a real environment I'd just take Spring, Hibernate etc.

So what I did was coding myself a small generic Data Access Layer with POJOs, working with generic methods to retrieve, check or insert data to the database (Oracle). Most of this is done through PreparedStatements.

This is working as long as I don't have joins... is it possible to put in a Column as parameter?

Example:

Table A has Attribute X + others
Table B has Attribute Y + others

PreparedStatement with query SELECT * FROM A,B WHERE "A"."X" = ?

And then fill in "B"."Y" as the parameter...

The database doesn't throw me an error or exception, but the ResultSet returned after executing the statement is empty. Is it just not possible to do, or am I just missing some escaping?

I'm using PreparedStatement.setString(int index, String value) to fill in the parameter... in lack of ideas which other setX method I could use...

Again, in a real project I'd never code that myself, but rather use something like Spring or Hibernate and not re-invent the wheel, but I see it as an interesting exercise to code such a generic small data access layer myself.

like image 775
Schmiger Avatar asked Nov 15 '13 18:11

Schmiger


1 Answers

No, JDBC does not allow this. Only column values can be set. If you want to make dynamic changes to the sql statement you will have to do it before you create the PreparedStatement.

like image 192
ayax79 Avatar answered Oct 18 '22 07:10

ayax79