简体   繁体   English

如何使用不同的where条件在Python中创建sql查询

[英]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下图显示了用户输入和构建的查询在此处输入图像描述

code:代码:

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.

相关问题 具有大小写和不同条件的SQL查询 - SQL query with case and different conditions 如何在Python条件下创建不同的csv文件 - How to create different csv files in Python under conditions 如何在 python 中根据不同条件动态创建列表? - How to create list dynamically based on different conditions in python? Python:根据不同条件创建新列 - Python: Create a new column based on different conditions python使用query_1导致query_2,其中条件作为查询将在不同的sql server中运行 - python use query_1 result in query_2 where condition as both the query will run in different sql server SQL查询不会在“ where”条件下选择我需要的数据 - SQL query doesn't select the data that I need with 'where' conditions 如何转换 SQL 中的字符串列表查询 python 中的 WHERE? - How to convert list of string in SQL query WHERE in python? 如何执行sql查询包括python的时间间隔条件 - How to execute sql query include where condition of time interval by python 如何在where IN子句中替换python sql查询中的参数INT值? - How to substitute parameter INT value in python sql query in where IN clause? 如何创建具有不同颜色的 4 个条件的图 - How to create a plot with 4 conditions with different colors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM