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)