Laurie
Laurie

Reputation: 1229

Psycopg2 database class not returning object

I have a database class and I'm trying to extract all data from a table. When I run the function 'db_source', no object is generated. Other queries within the class work, so its specifically a problem with returning the object. Heres my code:

import psycopg2 as psy

class Database:
    def __init__(self):
         self.con = psy.connect(user='postgres',
                               password='xxxx',
                               database='xxxx',
                               host='localhost')
         self.cur = self.con.cursor()

    def execute_query(self, query, args, multiple=False, return_object=False):
        if not multiple and not return_object:
            self.cur.execute(query, args)

        if multiple:
            self.cur.executemany(query, args)

        if return_object:
            self.cur.execute(query, args)
            query_object = self.cur.fetchall()
            return query_object

    def db_source(self):
        self.execute_query(""" SELECT column1, column2::text, column3 FROM table1 """,
                               None, multiple=False, return_object=True)

db = Database()
data = db.db_source()

I've been pulling my hair out over this for an hour, so any help would be appreciated.

Upvotes: 0

Views: 668

Answers (1)

klin
klin

Reputation: 121834

The method has to return the object:

def db_source(self):
    return self.execute_query(""" SELECT column1, column2::text, column3 FROM table1 """,
                           None, multiple=False, return_object=True)

Upvotes: 1

Related Questions