简体   繁体   中英

Sending data from variable to sql query in pandas read_sql(')

I want to send start date and end date value into my sql query from 2 separate variables. Suppose, I have start_date = '2020-05-14' and end_date = '2020-07-08' stored in a variable. Now my query is:

db_connection_str = 'mysql+pymysql://username:password@host/table_name'
db_connection = create_engine(db_connection_str)
def myfunc(start_date, end_date):
    sql_syn = "SELECT col_id, col_a, col_b, date, FROM en_stat where date between :start_date and :end_date"
    sql_df = pd.read_sql(sql_syn, con=db_connection, chunksize=100)

how to pass the start_date and end_date values dynamically for this particular code.

Use python3 f-strings :

def myfunc(start_date, end_date):
    sql_syn = f"SELECT col_id, col_a, col_b, date, FROM en_stat where date between {start_date} and {end_date}"
    sql_df = pd.read_sql(sql_syn, con=db_connection, chunksize=100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM