Skip to content
Advertisement

Database Error: NameError: name ‘db’ is not defined. What am I doing wrong?

On the web I found this illustration to create a database with gui with Tkinter. Everything ok, except when I enter the data and click on the Add button. I’m getting: NameError: name 'db' is not defined

I think what I am wrong is nonsense in this part of the code. What am I doing wrong?

Here is my code uploaded su un editor online. I am writing it here because it is too long to enter. I am new and having difficulty with StackOverflow. If we can figure out the error, I’ll update the question with the code I’m wrong.

import sqlite3
conn = sqlite3.connect('/home/dekstop/db.db')
cur = conn.cursor()


class Database:
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.cur = self.conn.cursor()
        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")
        self.conn.commit()

    def fetch(self, hostname=''):
        self.cur.execute(
        "SELECT * FROM routers WHERE hostname LIKE ?", ('%'+hostname+'%',))
        rows = self.cur.fetchall()
        return rows

    def fetch2(self, query):
        self.cur.execute(query)
        rows = self.cur.fetchall()
        return rows

    def insert(self, hostname, brand, ram, flash):
        self.cur.execute("INSERT INTO routers VALUES (NULL, ?, ?, ?, ?)",
                     (hostname, brand, ram, flash))
        self.conn.commit()

    def remove(self, id):
        self.cur.execute("DELETE FROM routers WHERE id=?", (id,))
        self.conn.commit()

    def update(self, id, hostname, brand, ram, flash):
        self.cur.execute("UPDATE routers SET hostname = ?, brand = ?, ram = ?, flash = ? WHERE id = ?",
                     (hostname, brand, ram, flash, id))
        self.conn.commit()

    def __del__(self):
    self.conn.close()

Advertisement

Answer

You have this:

import sqlite3
conn = sqlite3.connect('/home/dekstop/db.db')
cur = conn.cursor()


class Database:
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.cur = self.conn.cursor()
        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")
        self.conn.commit()
        ...

Right away, you can see a problem there. You have conn and curr defined outside the class and inside. It seems clear that the rest of your code expects db to be an instance of the Database class. So you need:

import sqlite3

class Database:
    ... same as always ...

db = Database('/home/dekstop/db.db')

and you need to do that before any of the code that refers to db.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement