skip to Main Content

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.

2

Answers


  1. Let’s assume you have your own PostgreSQL database. You should have a specific table in that database called your_table, which consists of two columns named column_a and column_b. As a user, you will be asked to provide your preferred columns to be selected, choosing from options A, B, and C. Based on your input, the script will dynamically construct an SQL query that precisely selects the columns you specified.

    This is an example how you can do that easily:

    import psycopg2
    
    # Establish a connection to the PostgreSQL database
    conn = psycopg2.connect(database="your_database", user="your_user", password="your_password", host="your_host", port="your_port")
    cursor = conn.cursor()
    
    # User input
    user_input = input("Enter column(s) to select (A, B, C): ")
    columns = []
    
    # Check user input and build the list of columns to select
    if "A" in user_input:
        columns.append("column_a")
    if "B" in user_input:
        columns.append("column_b")
    
    # Build the SQL query
    if "C" in user_input:
        query = "SELECT column_a FROM your_table"
    else:
        query = f"SELECT {', '.join(columns)} FROM your_table"
    
    # Execute the query
    cursor.execute(query)
    results = cursor.fetchall()
    
    # Process the results
    for row in results:
        # Process each row as needed
        print(row)
    
    # Close the cursor and connection
    cursor.close()
    conn.close()
    
    

    I’m assuming you have psycopg2 installed, if not use pip install psycopg2.
    I hope you’ll find this helpful…

    Login or Signup to reply.
  2. 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};
    """ 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search