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?
? is for input values (typically in the
WHERE
clause conditions).? is not for selected columns.