0

I have this code here:

private void updateGame(String column, String player, String block, String state) {
        try {
            Connection conn = db.openConnection();
            PreparedStatement ps = conn.prepareStatement("UPDATE games SET ? = ? WHERE game_id = ?");
            ps.setString(1, column);
            ps.setString(2, block);
            ps.setInt(3, getGameId(state, player));
            ps.executeUpdate();
            conn.close();
        } catch (Exception ex) {
        }
    }

When I pass in the column parameter, I want it to update a specific column in the database that I wrote when calling the function. I have multiple columns that are similar and that's why I am using this method. However, when I do it this way, it just gives out an error. I tried setting the column directly, without a question mark (?), and it worked. Not a duplicate because of the reply i got that is a different solution to the one in the "duplicate"

Is there any way to do this?

Chormi
  • 13
  • 1
  • 6
  • what is the error? – m.antkowicz Jul 26 '19 at 22:38
  • I want to change the column I update by passing it when calling the function. However, I can't set it by using "?". I can only set a single column by directly writing it in the statement. – Chormi Jul 26 '19 at 22:40

2 Answers2

0

Unfortunately you can only bind column values to a PreparedStatement, not column names.

You could instead use a formatter to perform the substitution:

MessageFormat.format("UPDATE games SET {0} = ? WHERE game_id = ?", column)
IronMan
  • 1,854
  • 10
  • 7
0

Because of (pre)compiling the statement (where all the given tables and columns are involved), you may not bind column names.

Janos Vinceller
  • 1,208
  • 11
  • 25