2

I am trying to create a generalized UPDATE-statement like this, where only the table-name is fixed.

updateValueQuery = conn.prepareStatement("UPDATE TABLENAME SET (?)=(?)");

That fails with an SQLException complaining about syntax. As soon as I specify the column-name like this:

updateValueQuery = conn.prepareStatement("UPDATE TABLENAME SET COL_NAME=(?)");

SQL happily compiles. Is there any way to make the columnname anonymous as well?

I am using Apache derby.

Max Beikirch
  • 2,053
  • 5
  • 25
  • 36
  • Only by building it as a string and passing that to the prepareStatment method (with all the SQL injection issues that that entails) – davek Jul 16 '13 at 13:42
  • Almost `prepareStatement("?")`; so do your own templating, w.r.t. column names: `String.format("UPDATE TABLENAME SET %s=?", "COL_NAME") ` – Joop Eggen Jul 16 '13 at 13:49
  • Yes, that's the way I solved it. I hoped there was a cleaner way, but there obviously isn't :( – Max Beikirch Jul 16 '13 at 14:06

1 Answers1

2

No, PreparedStatement has holders for values only. I resolved similar problem in following way:

    private final String FIND_STRING = "select * from TABLENANE where {0} = ?";
       .
       .
       .
    private final Map<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();

    private PreparedStatement prepareStatement(String field, String toFind) throws SQLException{
       PreparedStatement statement = null;
       if (statements.contains(field)){
          statement = statements.get(field);
       }else{
          String findInHelpDefinition = MessageFormat.format(FIND_STRING, field));
          statement = connection.prepareStatement(findInHelpDefinition);
          statemnts.put(field, statement);
       }
       statement.setString(1, toFind);
       return statement;
    }
agad
  • 2,192
  • 1
  • 20
  • 32