1

I am new to python and programming in general. This bit of code will eventually be used in a larger application. I apologize ahead of time for any mistakes. I am trying to make a simple query from a table in a postgresql database. The only result comes back as None. Even though I know there is data there. Thank you in advance for any assistance.

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()

1 Answer 1

1

The problem is the quotes around the Track_Length and Track_ID. Because of the quotes, column names are currently interpreted as actual strings leading to an unsatisfied comparison between strings Track_ID and Daytona. Which leads to 0 rows matching the query and length getting the None value.

Remove the single quotes around the column names:

cur.execute("""
    SELECT Track_Length 
    FROM t_tracks
    WHERE Track_ID = 'Daytona'
""")
Sign up to request clarification or add additional context in comments.

1 Comment

Or use double quotes around table names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.