我有以下Python代码:
statement = statement + " OR (TIMESTAMPDIFF(MINUTE, (str_to_date( (SELECT tijd FROM Metingen WHERE SensorID='" + sensor_id + "' ORDER BY MetingID DESC LIMIT 1), '%%d-%%m-%%Y %%H:%%i' )), NOW()) >= " + waarde + " AND MetingID=(SELECT metingID FROM Metingen WHERE SensorID='" + sensor_id + "' ORDER BY metingID DESC LIMIT 1)"
我正在尝试使用str_to_date MySQL函数,但是因此我需要在MySQL查询中使用百分号,这是在Python中生成的。我知道使用%%
应该可以解决这个问题,但是当我这样做时,两个百分号都会打印到查询中,查询将无效。
答案 0 :(得分:0)
当我在代码中使用硬编码的SQL查询时,我喜欢将它们放在多行字符串中。 (参见字符串上的documentation)
QUERY = """
{prefix}
OR (
TIMESTAMPDIFF(MINUTE,
(str_to_date((
SELECT tijd
FROM Metingen
WHERE SensorID='{sensor_id}'
ORDER BY MetingID DESC LIMIT 1),
'%d-%m-%Y %H:%i' )),
NOW()) >= {waarde}
AND
MetingID=(
SELECT metingID
FROM Metingen
WHERE SensorID='{sensor_id}'
ORDER BY metingID DESC LIMIT 1)
""".strip()
statement = QUERY.format(
prefix=statement,
sensor_id=sensor_id,
waarde=waarde)