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
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 namedcolumn_a
andcolumn_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:
I’m assuming you have
psycopg2
installed, if not usepip install psycopg2
.I hope you’ll find this helpful…
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 ).