【发布时间】:2021-05-19 19:21:56
【问题描述】:
我正在尝试使用 psycopg2 进行非常基本的查询,但除非我对参数进行硬编码,否则它不会给我结果,我做错了什么?可能是我这里有午夜大脑,但我不这么认为......
这不起作用:
query = """SELECT TRIM(TRAILING FROM symbol) as symbol, timestamp, open, close, high, low, volume
FROM trades_1_min
WHERE symbol=%(symbol)s
ORDER BY id DESC LIMIT 1"""
with db_conn.cursor() as cursor:
cursor.execute(query, {'symbol': symbol})
res = cursor.fetchall()
cursor.close()
return res
return None
而如果我在输入 [... symbol='%(symbol)s' ...] 周围加上引号,我可以看到它实际上将查询参数放在那里,因为我收到以下错误:
Traceback (most recent call last):
File "testlol.py", line 22, in <module>
main()
File "testlol.py", line 20, in main
print(get_latest("amd"))
File "testlol.py", line 12, in get_latest
cursor.execute(query, {'symbol': symbol})
psycopg2.errors.SyntaxError: syntax error at or near "amd"
LINE 3: WHERE symbol=''amd''
现在,如果我只是在 psql 中运行查询,我就会得到答案。是的,我已连接到正确的数据库、正确的用户等。一个更简单的查询可以确认这一点。
import psycopg2
db_conn = psycopg2.connect(dbname="pi", user="pi", password="raspberry")
def lol():
cursor = db_conn.cursor()
cursor.execute('SELECT * FROM trades_1_min LIMIT 1')
res = cursor.fetchall()
print(res)
def get_latest(symbol):
query = """SELECT TRIM(TRAILING FROM symbol) as symbol, timestamp, open, close, high, low, volume
FROM trades_1_min
WHERE symbol=%(symbol)s
ORDER BY id DESC LIMIT 1"""
with db_conn.cursor() as cursor:
cursor.execute(query, {'symbol': symbol})
res = cursor.fetchall()
cursor.close()
return res
return None
def main():
lol()
#print(get_latest("amd"))
main()
这是表结构: Table structure
【问题讨论】:
-
函数
get_latest正在返回None,所以print(get_latest("amd"))将返回None。引用参数时您会看到一些东西,因为它在到达return None之前会引发异常,并且您会在回溯中看到该值。 -
但是它不返回None,它返回一个空列表。
-
@Joel Andersson:
get_latest由于语法错误而无法工作,第一个查询有什么问题? -
什么是语法错误?第一个查询(在 lol() 函数中只是为了表明数据库连接没有问题)。
-
我无法复制。在这里创建一个类似的函数是可行的。我唯一无法复制的是传入的
symbol值。您确定是您认为它是和/或WHERE symbol=%(symbol)s中不存在大小写差异吗?我已经通过将log_statement提高到'all'并查看查询到达服务器时的样子来解决这些问题。这会生成大量日志,因此您不希望将其保留那么久。
标签: python postgresql psycopg2 psql