如何将Sqlalchemy核心与文本sql一起用于日期范围?

2024-03-29 08:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

s = text('SELECT customers.id,WHERE customers.end_date IS NULL or customers.end_date >= '+ "2018-05-01"+ 'AND customers.end_date <='+"2018-05-31" + 'ORDER BY customers.id;')

这会引发语法错误。如何准确传递上述语句中的日期值?如何查找日期字符串?仅使用sqlalchemy core1.0.8版,Python2.7


Tags: orandtextiddatebyisorder
3条回答

存在多个潜在的语法错误。第一个是SELECT项列表末尾WHERE子句之前的额外逗号。第二个(和第三个)是您要比较的文本周围缺少的引号。缺少的空格也会改变查询的解析方式。字符串串联后,结果如下所示:

In [2]: s
Out[2]: 'SELECT customers.id,WHERE customers.end_date IS NULL or customers.end_date >= 2018-05-01AND customers.end_date <=2018-05-31ORDER BY customers.id;'

这显然是错误的。你知道吗

像往常一样,不要用字符串连接或格式将值传递给SQL查询,除非它们是静态的,在这种情况下,它们首先是查询的一部分。如果你这样做了,你可能会暴露在SQL injection之下。你正在使用的驱动程序比你更了解如何处理不同的数据类型、引用等。使用占位符:

s = text('''SELECT customers.id
            WHERE customers.end_date IS NULL
               OR customers.end_date >= :end_date_low
              AND customers.end_date <= :end_date_high
            ORDER BY customers.id''')
low = "2018-05-01"
high = "2018-05-31"

# engine, connection, or session
conn.execute(s, end_date_low=low, end_date_high=high)

此外,您还可以在以下两者之间使用SQL运算符:

s = text('''SELECT customers.id
            WHERE customers.end_date IS NULL
               OR customers.end_date BETWEEN :end_date_low AND :end_date_high
            ORDER BY customers.id''')

试试这个:

    s = text('SELECT customers.id WHERE customers.end_date IS NULL or 
   customers.end_date >= \'2018-05-01\' AND customers.end_date 
    <= \'2018-05-31\' ORDER BY customers.id;')

连接字符串时要小心,可能会丢失一些空格。例如: "2018-05-01"+ 'AND customers.end_date <='=>;"2018-05-01AND customers.end_date <='。 等等

另一件事是在查询中添加日期前后的引号。 在您的情况下,引号不是查询的一部分。 所以你可以写: "'2018-05-01'"+ ' AND customers.end_date <='。你知道吗

或者看@Dataichou的完整示例

相关问题 更多 >