Where should ? be placed in a PreparedStatement?

122 views Asked by At

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?

2

There are 2 answers

0
jarlh On BEST ANSWER

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

? is not for selected columns.

2
Sachin Gupta On

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 = ?";