【发布时间】:2019-03-17 09:59:45
【问题描述】:
我正在从 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 的情况下,我希望将条件全部忽略。
替换方法是在 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)
【问题讨论】:
-
您可能有兴趣使用模板语言(如github.com/hashedin/jinjasql)以更易读和可维护的方式创建 sql
标签: python sql pandas replace pyodbc