CodeTalk
CodeTalk

Reputation: 3667

How to use my class 'database' in another class?

I'm newer to OOP in Python, and have been trying for awhile to use my database class database within another class.

How can I do so?

class database(object):
    def connect_db(self):
        try:
            import sqlite3 as sqli
            connection = sqli.connect('pw.db')
            cur = connection.cursor()
        except:
            print("There was an error connecting to the database.")

I've been trying to like this, but it doesnt work:

 import db_helper as dbh
    class account_settings(object):
                def create_account(self):
        setting_username = input('\nUsername?\n')
        setting_password = input('\nPassword?\n')

        cur = db.connect_db()
        with cur:
            cur.execute('''
                CREATE TABLE IF NOT EXISTS my_passwords(
                    id INTEGER PRIMARY KEY AUTOINCREMENT NULL,
                    password text UNIQUE
                )
            ''')
            try:
                cur.execute('INSERT INTO my_passwords(password) VALUES(?)', (self.create_password(),) )
            except:
                print("Error occurred trying to insert password into db. Please retry")

    c = account_settings()
    c.create_account()

new error:

  File "settings.py", line 30, in <module>
    c.create_account()
  File "settings.py", line 15, in create_account
    with cur:
AttributeError: __exit__

Upvotes: 0

Views: 1468

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You need to learn about variable scope. db.connect_db() creates a cursor connection with the name cur, but does not do anything with it; when that method finishes, the object is destroyed. In particular, it never makes it back to the create_account method.

There is a simple way to solve this: return the object back to the method, and use it there.

def connect_db(self):
    ...
    cur =  connection.cursor()
    return cur

...
def create_account(self):
    cur = db.connect_db()
    with cur:

or even beter:

with db.connect_db()

Note that really, neither of these should be classes. Classes in Python are really only useful when you're keeping some kind of state, which isn't happening here. connect_db and create_account should just be standalone functions in their respective modules.

Upvotes: 1

Related Questions