0

In a university task I'm using JDBC to access a database. I wrote a finder-method that could find objects in a table by any value in any column that has integer values.

public ResultSet findSampleByAnyCol(String colName, Integer sampleId, Connection con) {
    ResultSet rs = null;
    String sql = "SELECT * FROM sample WHERE ? = ?"; 

    try(PreparedStatement pstmt = con.prepareStatement(sql)) {
        pstmt.setString(1, colName);
        pstmt.setInt(2, sampleId);
        rs = pstmt.executeQuery();          

    }catch(SQLException e) {
        e.printStackTrace();
    }

    return rs;
  }

I tested it and I'm sure the problem is that "?" for the colum nname doesn't work. The stack trace says "invalid number". But if I change the SQL statement to SELECT * FROM sample WHERE sampleid = ? it works fine.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Severus0191
  • 39
  • 1
  • 8

1 Answers1

0

Just found the answer here, it´s not possible to do that. The "?" is just for values. To have variable columnnames it´s inevitable to do it with an own string manipulation.

Severus0191
  • 39
  • 1
  • 8