<p>存在多个潜在的语法错误。第一个是SELECT项列表末尾WHERE子句之前的额外逗号。第二个(和第三个)是您要比较的文本周围缺少的引号。缺少的空格也会改变查询的解析方式。字符串串联后,结果如下所示:</p>
<pre><code>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;'
</code></pre>
<p>这显然是错误的。你知道吗</p>
<p>像往常一样,不要用字符串连接或格式将值传递给SQL查询,除非它们是静态的,在这种情况下,它们首先是查询的一部分。如果你这样做了,你可能会暴露在<a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow noreferrer">SQL injection</a>之下。你正在使用的驱动程序比你更了解如何处理不同的数据类型、引用等。使用占位符:</p>
<pre><code>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)
</code></pre>
<p>此外,您还可以在以下两者之间使用SQL运算符:</p>
<pre><code>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''')
</code></pre>