我正在从python中从SQL Server提取记录:
REGION = 'HK'
.
.
where
R.rfq_create_date_time >= '""" + START_DATE + """'
and R.rfq_create_date_time <= '""" + END_DATE + """'
and R.latest_version = 'Y'
and R.sales_book in ('""" + sales_code_string + """')
and R.Trading_book in ('""" + Trading_Books + """')
) as innerTable
WHERE rfq_create_time not between '""" + START_TIME + """' and '""" + END_TIME + """'
order by rfq_create_time"""
print (strSql)
print("")
df_With_NaN = pd.read_sql(strSql, pyodbc.connect(connstr))
如果REGION
是HK或SY,我只希望字符串中包含的and R.Trading_book in
条件传递给我的连接。在TK的情况下,我希望条件一起被忽略
replace方法是在python中实现这一点的最佳方法还是有替代方法?例如:
REGION = "TK"
strsql = "select * from table where ccy = 'AAA' ######"
if REGION == "HK":
booklist = "'AAA','BBB','CCC'"
elif REGION == "SY":
booklist = "'CCC','DDD','FFF'"
if REGION == "TK":
strsql = strsql.replace("######", "")
else:
strsql = strsql.replace("######", " and book in (" + booklist + ")")
print (strsql)
另一种可能更具可读性的方法是
或者,如果您使用的是python3.6或更高版本,您可以这样做
相关问题 更多 >
编程相关推荐