Home > Mobile >  PostgresSQL query returns None in Python (Works on PgAdmin)
PostgresSQL query returns None in Python (Works on PgAdmin)

Time:10-01

I have the following query:

def is_paying_user(user_id: int) -> bool:
    with Database() as cursor:
        res = cursor.execute(f"""SELECT is_paying FROM public."Users" WHERE user_id = {user_id}""")
        return res.fetchone()

user_id is an integer.

Database is a context manager defined as:

class Database:
    def __init__(self):
        self.connection = psycopg2.connect(database="postgres", user=DB_USER, password=DB_PASS,
                                           host=LOCALHOST, port=DB_PORT)

    def __enter__(self):
        return self.connection.cursor()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connection.commit()
        self.connection.close()

And I am getting the following error when calling is_paying_user:

AttributeError: 'NoneType' object has no attribute 'fetchone'

When I grab the integer value and run the same query on PgAdmin it succeeds.

I also tried a few variations of the same query (got same error):

cursor.execute("""SELECT trackables_amount FROM public."Users" WHERE user_id = %s""", (user_id,))

cursor.execute("""SELECT trackables_amount FROM public."Users" WHERE user_id = %s""", user_id)

CodePudding user response:

The return value of cursor.execute is undefined; you want to call .fetchall (or .fetchone) on the cursor object!

  • Related