0

I have this sql statement:

selectAllUsersByCriteria = connection.prepareStatement( "SELECT * FROM Users WHERE ? = ?" );

And the follow method running the statement:

public ArrayList<User> getUsersByCriteria(String 1criteria, String 2criteria)
{
    ArrayList<User> results = null;
    ResultSet resultSet = null;
    try 
    {
        selectAllUsersByCriteria.setString( 1, 1criteria);
        selectAllUsersByCriteria.setString( 2, 2criteria);

        // executeQuery returns ResultSet containing matching entries
        resultSet = selectAllUsersByCriteria.executeQuery(); 

        results = new ArrayList< User >();

        while ( resultSet.next() )
        {
            results.add( new User( resultSet.getString( "userName" ),
                    resultSet.getString( "Password" ),
                    resultSet.getBoolean( "AdminRights" ),
                    resultSet.getDouble( "Balance" )
                    ) );
        } // end while
    } // end try
    catch ( SQLException sqlException )
    {
        sqlException.printStackTrace();
    } // end catch
    finally
    {
        try 
        {
            resultSet.close();
        } // end try
        catch ( SQLException sqlException )
        {
            sqlException.printStackTrace();         
            close();
        } // end catch
    } // end finally

    return results;
} 

It doesn't work. I figure it is the first ? that is the issue. Isn't it possible to set the WHERE ? as a ?. Can it be solved in another way.

It is a table I want to show, but it should only be show the users follow it meet the two criteria.

MDK
  • 95
  • 1
  • 1
  • 8

1 Answers1

0

You would need to inject the column name directly into the string. That would open you up to a SQL injection attack, so I'd recommend querying (and probably caching) the table's schema info (specifically found in INFORMATION_SCHEMA.COLUMNS).

This way you can make sure that your user-submitted column name matches one of the column names in your table before injecting it into the script by seeing if it's in your list of available columns.

Dave
  • 900
  • 6
  • 22