cc. cc. - 4 months ago 13
MySQL Question

PreparedStatement: Can I supply the column name as parameter?

Let's say I have a table with 3 columns: C1, C2, C3

I make a search based on the C1 column.
Could I make something similar like this (this is not working - because this is not the way prepareStatement it's used:) )

String c;// the name of the column

String sql = "select * from table where ? = ?";
pre = con.prepareStatement(sql);
pre.setString(1, c);
pre.setString(1, i);
rs = pre.executeQuery();

The main idea, I don't want to have 3 ifs for every column. An elegant solution?


you could code up a a set of sql queries and store them in a map, then grab one based on the column in question.

enum column { a, b, c}

Map<column, string> str;

static {
 str.put(a, "select * from tbl where a = ? ");

then just grab one out of the map later based on the enum. String appends in sql statements have a way of becoming security problems in the future.