在 SQL 查询中使用变量
Use variable in SQL query
我想创建一个设置为当前时间的变量 now
,然后在我的 psycopg2 查询中使用它。我试过按以下方式使用 python 的 datetime
和 current_timestamp
,但它会产生错误并且无法识别变量:
@app.route('/_ajax', methods=['GET', 'POST'])
def userCount():
now = current_timestamp
cur.execute("""SELECT count(DISTINCT(username)) from user_table WHERE tstampz >
(now - INTERVAL '60 mins')""")
userCount=cur.fetchone()[0]
return jsonify (userCount=userCount)
如果我使用 datetime.datetime.now
而不是 current_timestamp
,则会出现无法索引 datetime
的错误报告。如何正确设置此变量?
澄清一下:我不想在查询中直接使用 current_timestamp
或 'now()` 的原因是时间 default当前时间,但它会在某个时候更改(基于用户输入),因此更改查询。
我认为查询应该是:
SELECT count(DISTINCT username)
from user_table
WHERE tstampz > (now() - INTERVAL '60 mins')
请注意 now()
是一个函数,而不是 Postgres 中的 "variable"。
如果要在 Python 中执行此操作,则需要参数化查询。 (查看您的文档以了解详细信息;您可能需要与我展示的略有不同的内容。)
@app.route('/_ajax', methods=['GET', 'POST'])
def userCount():
now = datetime.now()
cur.execute("""SELECT count(DISTINCT(username)) from user_table WHERE tstampz >
(%s - INTERVAL '60 mins')""", (now,))
userCount=cur.fetchone()[0]
return jsonify (userCount=userCount)
您接受的答案显示了正确参数化的查询。但是,您应该注意,PostgreSQL 知道当前时间,并且您 运行 使用来自客户端的时间时区混淆的风险。如果您真的需要最后一个小时的行,一个更安全的查询是
SELECT count(DISTINCT(username)) from user_table WHERE tstampz >
(current_timestamp - INTERVAL '60 mins')
有些奇怪的是,the documentation 将 current_datetime
列为函数,但您会发现如果添加括号来调用它,则会出现语法错误。
我想创建一个设置为当前时间的变量 now
,然后在我的 psycopg2 查询中使用它。我试过按以下方式使用 python 的 datetime
和 current_timestamp
,但它会产生错误并且无法识别变量:
@app.route('/_ajax', methods=['GET', 'POST'])
def userCount():
now = current_timestamp
cur.execute("""SELECT count(DISTINCT(username)) from user_table WHERE tstampz >
(now - INTERVAL '60 mins')""")
userCount=cur.fetchone()[0]
return jsonify (userCount=userCount)
如果我使用 datetime.datetime.now
而不是 current_timestamp
,则会出现无法索引 datetime
的错误报告。如何正确设置此变量?
澄清一下:我不想在查询中直接使用 current_timestamp
或 'now()` 的原因是时间 default当前时间,但它会在某个时候更改(基于用户输入),因此更改查询。
我认为查询应该是:
SELECT count(DISTINCT username)
from user_table
WHERE tstampz > (now() - INTERVAL '60 mins')
请注意 now()
是一个函数,而不是 Postgres 中的 "variable"。
如果要在 Python 中执行此操作,则需要参数化查询。 (查看您的文档以了解详细信息;您可能需要与我展示的略有不同的内容。)
@app.route('/_ajax', methods=['GET', 'POST'])
def userCount():
now = datetime.now()
cur.execute("""SELECT count(DISTINCT(username)) from user_table WHERE tstampz >
(%s - INTERVAL '60 mins')""", (now,))
userCount=cur.fetchone()[0]
return jsonify (userCount=userCount)
您接受的答案显示了正确参数化的查询。但是,您应该注意,PostgreSQL 知道当前时间,并且您 运行 使用来自客户端的时间时区混淆的风险。如果您真的需要最后一个小时的行,一个更安全的查询是
SELECT count(DISTINCT(username)) from user_table WHERE tstampz >
(current_timestamp - INTERVAL '60 mins')
有些奇怪的是,the documentation 将 current_datetime
列为函数,但您会发现如果添加括号来调用它,则会出现语法错误。