Home:ALL Converter>SQLalchemy trying to connect to postgresql using oop

SQLalchemy trying to connect to postgresql using oop

Ask Time:2016-08-19T02:12:57         Author:hselbie

Json Formatter

I'm trying to teach myself a bit of OOP and as a test i'm trying to create a class that will connect to an existing postgresql database i've created.

I can connect to the database fine using sqlalchemy if I use this code

engine = create_engine('postgresql://user@localhost/dbname')
conn = engine.connect()
result = conn.execute(sql)
for row in result:
    print(row)

However, as I mentioned i'm new to OOP so trying to figure out how to replicate this in a class format. The following code gives the error AttributeError: 'NoneType' object has no attribute 'execute'. I imagine there are many errors and best practices i'm missing out on so some kind of guidance would be much appreciated.

from sqlalchemy import create_engine

class dbConnect(object):
    db_connection = None
    db_cur = None

    def __init__(self):
        self.db_connection = create_engine('postgresql://user@localhost/dbname')
        self.cur = self.db_connection.connect()

    def query(self, query):
        test = self.db_cur.execute(query)
        return test

sql = """
SELECT
    id
FROM
    t
WHERE
    id = 14070
"""

x = dbConnect()
result = x.query(sql)
for row in result:
    print(row)

Author:hselbie,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39024897/sqlalchemy-trying-to-connect-to-postgresql-using-oop
yy