如何在python代码中的sql命令中参数化字符串的一部分?

问题描述 投票:0回答:2

我有一个SQL查询:

cur.execute("copy tmp from 's3://orders/20200515/orders.csv") 

我如何参数化查询的/ 20200515 /部分?

类似:

list1=['20200515','20200516','20200517']
for A in list1:
   cur.execute("copy tmp from 's3://orders/A/orders.csv") 
python python-3.x list parameter-passing
2个回答
0
投票

您可以使用str.format

list1 = ['20200515','20200516','20200517']
for A in list1:
   cur.execute("copy tmp from 's3://orders/{}/orders.csv".format(A))

请参阅official documentation了解更多信息。


0
投票

自python 3.6起,您可以使用f字符串。 https://www.python.org/dev/peps/pep-0498/

list1 = ['20200515','20200516','20200517']
for A in list1:
   cur.execute(f"copy tmp from 's3://orders/{A}/orders.csv")

F字符串比其他字符串格式化机制更有效

© www.soinside.com 2019 - 2024. All rights reserved.