【问题标题】:Storing a sql query as a single variable in Python [duplicate]在Python中将sql查询存储为单个变量[重复]
【发布时间】:2017-03-29 16:08:18
【问题描述】:

我正在尝试编写一些调用 SQL 查询的 Python 代码,以允许 SQL 查询保持我想要的格式,但是 Python(我使用的是 Spider GUI)到达行尾并识别字符串没有结束。

假设我在表 database.table 中的数据如下所示:

ID Date Amount
1 2016-10-01 $3.00
1 2016-10-05 $4.99
1 2016-10-12 $1.29
2 2016-08-12 $50.13
2 2016-09-11 $27.89
2 2016-10-08 $31.13
3 2016-10-04 $4.18
3 2016-10-10 $43.99
3 2016-10-20 $62.11

如果我编写多行代码并尝试将其传递给 Python 中的单个变量,则会遇到 EOF 错误。

Date1 = '2016-10-01'
Date2 = '2016-10-10'

TD_Code_Snipit = str("select 
ID,
sum(Amount) as Amount
from database.tablename
group by ID
where Date >="
+Date1+
str(" and  Date < ")
+Date2+
str(";")

这使我的代码具有可读性(我想要输入的真正查询大约是 80 行,因此将其放在一行代码中会使得动态调整变得相当困难。

这是解决此问题的固有错误方法,还是 Spider 中的设置使其无法正确换行导致错误?

【问题讨论】:

标签: python string


【解决方案1】:

我认为这就是您所需要的。对于多行,您需要''',对于变量,您可以使用{} 占位符。

Date1 = '2016-10-01'
Date2 = '2016-10-10'

TD_Code_Snipit = '''select 
ID,
sum(Amount) as Amount
from database.tablename
group by ID
where Date >= {}
 and  Date < {}
;'''.format(Date1, Date2)

【讨论】:

    猜你喜欢
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2016-06-21
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多