how to create sql query in Python with different where conditions

Viewed 193

I have a python code that create sql query in order to allow the user to filter the required data from a database.

Until now I am able to create a query using function.

The problem is that the logical operators or/and are the same for all fields

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 enter image description here

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)
1 Answers

Take a look at SQLAlchemy

I've never used pyodbc to be honest and I'm not sure if you have any constraint that makes you use it. 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.

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.

Related