psycopg2 查询 returns None
psycopg2 query returns None
我不熟悉 python 和一般的编程。这段代码最终将用于更大的应用程序。对于任何错误,我提前道歉。我正在尝试从 postgresql 数据库中的 table 进行简单查询。返回的唯一结果为 None。即使我知道那里有数据。提前感谢您的帮助。
import psycopg2
def connect():
"""Connects to the database so you can query the stats you require"""
conn= psycopg2.connect("dbname='Nascar_Stats' user='postgres' \
host='localhost' password='xxxxxxxx'")
print('Connected to DB')
cur = conn.cursor()
cur.execute("SELECT 'Track_Length' FROM t_tracks \
WHERE 'Track_ID' = 'Daytona';")
length = cur.fetchone()
print('Track Length = ', length)
conn.close()
问题是 Track_Length
和 Track_ID
周围的引号。由于引号,列名当前被解释为实际字符串,导致字符串 Track_ID
和 Daytona
之间的比较不令人满意。这导致 0 行与查询匹配并且 length
获得 None
值。
删除列名称周围的单引号:
cur.execute("""
SELECT Track_Length
FROM t_tracks
WHERE Track_ID = 'Daytona'
""")
我不熟悉 python 和一般的编程。这段代码最终将用于更大的应用程序。对于任何错误,我提前道歉。我正在尝试从 postgresql 数据库中的 table 进行简单查询。返回的唯一结果为 None。即使我知道那里有数据。提前感谢您的帮助。
import psycopg2
def connect():
"""Connects to the database so you can query the stats you require"""
conn= psycopg2.connect("dbname='Nascar_Stats' user='postgres' \
host='localhost' password='xxxxxxxx'")
print('Connected to DB')
cur = conn.cursor()
cur.execute("SELECT 'Track_Length' FROM t_tracks \
WHERE 'Track_ID' = 'Daytona';")
length = cur.fetchone()
print('Track Length = ', length)
conn.close()
问题是 Track_Length
和 Track_ID
周围的引号。由于引号,列名当前被解释为实际字符串,导致字符串 Track_ID
和 Daytona
之间的比较不令人满意。这导致 0 行与查询匹配并且 length
获得 None
值。
删除列名称周围的单引号:
cur.execute("""
SELECT Track_Length
FROM t_tracks
WHERE Track_ID = 'Daytona'
""")