Search code examples
pythonpostgresqldataframeflasklogic

Python: The best way to select columns in SQL based on the User input


I have 2 columns in the table, Column A and Column B

User inputs: A, B, C

User can give any of the above inputs.

If user input is A then column B needs to be selected. If user input is B then column A and Column B needs to be selected. If user input is C then column A needs to be selected.

Thanks in advance.


Solution

  • One of ways to do this in python is to define your own dictionary (dict), that maps user input to desired columns to select based on this , so the code will be some how like this ( it's the general logic regardless the way you connect to database , and how you are willing to execute the query ).

    TABLE_NAME = ''
    
    # this dict maps user selection to desired columns as mentioned 
    mp = {
        'A' : 'B',
        'B' : 'A,B',
        'C' : 'A'
    }
    
    user_input = 'A' # the selected value received from the user 
    desired_columns = mp[user_input] # get the desired columns based on user input 
    
    query = f"""
    SELECT {desired_columns}
    FROM {TABLE_NAME};
    """