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};
"""
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()
2条答案
按热度按时间hiz5n14c1#
在python中实现这一点的方法之一是定义自己的字典(dict),它将用户输入Map到所需的列以基于此进行选择,因此代码将是这样的(无论您连接到数据库的方式如何,以及您愿意如何执行查询,这都是通用逻辑)。
bvn4nwqk2#
假设你有自己的PostgreSQL数据库。您应该在该数据库中有一个名为
your_table
的特定表,它由两个名为column_a
和column_b
的列组成。作为用户,系统将要求您提供要选择的首选列,从选项A、B和C中进行选择。根据您的输入,脚本将动态地构造一个SQL查询,该查询将精确地选择您指定的列。这是一个例子,你可以很容易地做到这一点:
我假设你已经安装了
psycopg2
,如果没有,就使用pip install psycopg2
。我希望你会发现这有帮助...