[英]how to create sql query in Python with different where conditions
I have a python code that create sql query in order to allow the user to filter the required data from a database.我有一个 python 代码创建 sql 查询,以便允许用户从数据库中过滤所需的数据。
Until now I am able to create a query using function.到目前为止,我可以使用 function 创建查询。
The problem is that the logical operators or/and
are the same for all fields问题是所有字段的逻辑运算符or/and
都相同
Query: name.str.contains('') or nickname.str.contains('') or mother_name.str.contains('') or first_nationality == 'None'
what i want is to be able to create different logical operator for each field like this:我想要的是能够为每个字段创建不同的逻辑运算符,如下所示:
Query: name.str.contains('') or nickname.str.contains('') and mother_name.str.contains('') or first_nationality == 'None'
the image below show the user input and the constructed query下图显示了用户输入和构建的查询
import streamlit as st
import pandas as pd
#SQL pckgs
import pyodbc
def build_query(input_values, logical_op, compare_op):
query_frags = []
for k, v in input_values.items():
if v['dtype'] == list:
query_frag_expanded = [f"{v['db_col']} {compare_op} '{val}'" for val in v['value']]
query_frag = f' {logical_op} '.join(query_frag_expanded)
elif v['dtype'] == int or v['dtype'] == float:
query_frag = f"{v['db_col']} {compare_op} {v['dtype'](v['value'])}"
elif v['dtype'] == str:
query_frag = f"{v['db_col']}.str.contains('{v['dtype'](v['value'])}')"
else:
query_frag = f"{v['db_col']} {compare_op} '{v['dtype'](v['value'])}')"
query_frags.append(query_frag)
query = f' {logical_op} '.join(query_frags)
return query
def configure_query():
c1, c2, _ = st.columns([1,1,2])
with c1:
logical_op = st.selectbox('Logical operator', options=['and', 'or'], index=1)
with c2:
compare_op = st.selectbox('Comparator operator', options=['==', '>', '<', '<=', '>='], index=0)
return logical_op, compare_op
logical_op, compare_op = configure_query()
query = build_query(input_values, logical_op, compare_op)
Take a look at SQLAlchemy看看SQLAlchemy
I've never used pyodbc to be honest and I'm not sure if you have any constraint that makes you use it.老实说,我从来没有使用过 pyodbc,我不确定你是否有任何限制让你使用它。 I normally use Sqlalchemy to create a connection to a database (my case is PostgreSQL) and then I use pd.read_sql(QUERY,con)
where con is the connection I've created with Sqlalchemy and QUERY is a string that represents the sql query.我通常使用 Sqlalchemy 创建到数据库的连接(我的案例是 PostgreSQL),然后我使用pd.read_sql(QUERY,con)
其中 con 是我用 Sqlalchemy 创建的连接,QUERY 是代表 sql 查询的字符串.
If you do that you would be able to easily create a function that receives the conditions you want to add and pass it to the query text.如果这样做,您将能够轻松创建一个 function,它接收您要添加的条件并将其传递给查询文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.