时间戳作为sql查询中的变量

时间:2018-05-29 20:10:34

标签: python mysql

我想在python中使用timestamp-value作为MySQL查询的变量。

tsmin = 1527573750;
tsmax = 1527574050;
command = "SELECT * FROM #CMD# WHERE data.#CMD#.TimesTamp BETWEEN 
          FROM_UNIXTIME(tsmin) AND FROM_UNIXTIME(tsmax)";

这会出现此错误:_mysql_exceptions.OperationalError:(1054,"未知列' tsmin'在' where子句'")

当我使用以下命令时,它可以正常工作。

command = "SELECT * FROM #CMD# WHERE data.#CMD#.TimesTamp BETWEEN 
          FROM_UNIXTIME(1527573750) AND FROM_UNIXTIME(1527574050)"

任何可以帮助我的人?​​

1 个答案:

答案 0 :(得分:0)

f-strings (Python 3.6+)

tsmin = 1527573750;
tsmax = 1527574050;
command = f"SELECT * FROM #CMD# WHERE data.#CMD#.TimesTamp BETWEEN 
          FROM_UNIXTIME({tsmin}) AND FROM_UNIXTIME({tsmax})";

格式

tsmin = 1527573750;
tsmax = 1527574050;
command = "SELECT * FROM #CMD# WHERE data.#CMD#.TimesTamp BETWEEN 
          FROM_UNIXTIME({tsmin}) AND FROM_UNIXTIME({tsmax})".format(tsmin=tsmin, tsmax=tsmax);