4

I am using PreparedStatement to select records from a table:

public static String getMemberInfo(String columnName, Integer memberId) {       
    String memberInfo = "";
    String sql = "SELECT ? FROM member WHERE member_id = ?";
    DatabaseConnector.setConn();

    try(Connection conn = DatabaseConnector.getConn();
        PreparedStatement ps = conn.prepareStatement(sql)) {

        ps.setString(1, columnName);
        ps.setInt(2, memberId);

        try(ResultSet rs = ps.executeQuery()) {
            if(rs.next()) {
                memberInfo = rs.getString(columnName);
            }
        }

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

    return memberInfo;
}

When I use SELECT " + columnName + " FROM member WHERE member_id = ?, it works.

But when I use SELECT ? FROM member WHERE member_id = ?, it does not.

Where should ? be placed in prepared statements?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

4

? is for input values (typically in the WHERE clause conditions).

? is not for selected columns.

jarlh
  • 42,561
  • 8
  • 45
  • 63
2

Column name must be hard-coded, Only column values can be set using ?.

but you can set dynamic column name by doing something like this :

String sql = "SELECT "+ columnName +" FROM member WHERE member_id = ?";
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • 2
    The restriction doesn't come from JDBC. It's the database that does not allow parameterised column names. Mostly because it cannot prepare a query plan without knowing the column and table names. – Andomar Jun 08 '15 at 06:32
  • Oh ok thanks for the info @Andomar I have removed that line from my answer. – Sachin Gupta Jun 08 '15 at 06:33