Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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)
share|improve this question
1  
Well, you've assigned db_cur = None but you subsequently want to call .execute(query) on it. – univerio Aug 18 at 18:15
    
Well, that was easy. you're correct and it works now. Thanks. Would still love to know if there are any best practices with this type of thing. – hselbie Aug 18 at 18:21
    
Best practices with this type of thing are called patterns, so you may want to look into "factory" or "singleton", both of which might be applicable here. Good luck! – Boris Shchegolev Aug 18 at 18:52

I always use Pajlada's Database Manager Singleton Class. It's pretty easy to get going. All you need to do is initialize the class with your URL.

DBManager.init('psqlurlhere')

and then whenever you want to create a session there are multiple ways to do it:

Create a session that will end after you do certain thing

with DBManager.create_session_scope() as session:
    session.add(Model)
    session.commit()

Create a session that you will reuse throughout your program:

session = DBManager.create_session(expire_on_commit=False)
session.add(Model)
session.comit()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.