简体   繁体   中英

how to pass an external variable to a query in python

how to pass an external variable to a query in python? Under my code

import openpyxl
import numpy as n
import pandasql as ps
from openpyxl import Workbook
import datetime
import pandas as pd


df2 = pd.read_excel(r'Desktop\esempio__base__2022032040_SIM.xlsx', sheet_name="quotazioni")
df3 = pd.read_excel(r'Desktop\esempio__base__2022032040_SIM.xlsx', sheet_name="polizze")
df4 = pd.read_excel(r'Desktop\esempio__base__2022032040_SIM.xlsx', sheet_name="att")

dataf2 = pd.DataFrame(df2)
dataf3 = pd.DataFrame(df3)
dataf4 = pd.DataFrame(df4)


data_ultimo_valore_quota_1 ="SELECT max(dataf2.d_riferimento) FROM dataf2, dataf3 where dataf3.NAV = dataf2.i_quotazione "
data_ultimo_valore_quota=(ps.sqldf(data_ultimo_valore_quota_1))
controvalore_iniziale =  "SELECT d_inizio FROM dataf4 where  d_inizio < %(data_ultimo_valore_quota)s "

I want to pass the variable in the last query: data_ultimo_valore_quota

It looks like you're trying to perform string formatting. Python provides multiple ways to do this. See https://realpython.com/python-f-strings/ for some options.

In your case, one option is to do something like

controvalore_iniziale = f"SELECT d_inizio FROM dataf4 where d_inizio < {data_ultimo_valore_quota}"

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