我正在尝试比较两个日期时间,并显示sql语法错误
from flask import Flask
from flask import request, jsonify
from datetime import datetime
import pymysql
app = Flask(__name__)
class Database:
def __init__(self):
host = "localhost"
user = "test"
password = "test123"
db = "test"
self.con = pymysql.connect(host=host, user=user, password=password, db=db, cursorclass=pymysql.cursors.DictCursor)
self.cur = self.con.cursor()
@app.route('/getCameraTypeAndTime/<string:date1>/<string:date2>', methods=['GET'])
def getCameraTypeAndTime(date1,date2):
start = datetime.strptime(date1, '%Y-%m-%d %H:%M:%S')
end = datetime.strptime(date2, '%Y-%m-%d %H:%M:%S')
db=Database()
result1=db.cur.execute("Select camera, COUNT(*) as freq from face_log group by camera where timestamp>start and timestamp_end<end")
return jsonify({'result': result1})
if __name__ == '__main__':
app.run(debug=True)
sql中的格式为日期时间,但不会比较
主要问题是您试图将列值与START
和END
MySQL keywords进行比较,而不是将start
和end
变量进行比较。您需要使用占位符进行查询,然后将变量传递给它(按照PyMySQL documentation):
db.cur.execute("""
SELECT camera, COUNT(*) AS freq FROM face_log
WHERE timestamp > %s and timestamp_end < %s
GROUP BY camera
""", start, end)
还请注意,SQL查询的GROUP BY
部分必须在WHERE
部分之后。