0

I am trying to make a query that takes all the values of a column, which can be username or email (using the columnName variable). Initially I had a normal query, but after reading more I found out that I should do a PreparedStament. However, the preparedStatement.setString(1, columnName) call it doesn't seem to work considering I have a for loop below and it doesn't display anything.

public class EmailOrUsernameAuthenticityVerifier {

    public EmailOrUsernameAuthenticityVerifier(
        String profileEmailOrUsername, String columnName) 
    throws SQLException, ClassNotFoundException, 
           EmailOrUsernameAlreadyExistException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn =
            DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", 
                                        "username", "password");

        PreparedStatement preparedStatement = 
            conn.prepareStatement("SELECT ? FROM profile");
        preparedStatement.setString(1, columnName);

        ResultSet rs = preparedStatement.executeQuery();

        Set<String> columnNameSet = new HashSet<>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnNumber = rsmd.getColumnCount();
        while (rs.next()) {
            for (int i = 1; i <= columnNumber; i++) {
                String columnValue = rs.getString(i);
                columnNameSet.add(columnValue);
            }
        }

        // This for is just for testing 
        for (String s: columnNameSet) {
            System.out.println(s);
        }
        
        if (columnNameSet.contains(profileEmailOrUsername)) {
            throw new EmailOrUsernameAlreadyExistException(
                profileEmailOrUsername);
        }
    }
}
Stephen C
  • 669,072
  • 92
  • 771
  • 1,162
  • Perhaps you want `select * from profile`? – jarlh Aug 31 '21 at 12:20
  • 1
    Does this answer your question? [Mysqli prepared statement column with variable](https://stackoverflow.com/questions/41598080/mysqli-prepared-statement-column-with-variable) Or this? [How to use prepare() with dynamic column names?](https://stackoverflow.com/questions/30939418/how-to-use-prepare-with-dynamic-column-names/30939945) – David Aug 31 '21 at 12:21
  • No, I just want a specified column (username or email) – Daniel Dănilă Aug 31 '21 at 12:21
  • 1
    You can't use `?` for column names. – forpas Aug 31 '21 at 12:22
  • You need to select **both** columns, and then pick the value that you need out of the resultset. (Or use two `PreparedStatements` / query strings.) – Stephen C Aug 31 '21 at 12:29

0 Answers0