Search code examples
pythonattributesnonetype

Python: dbcur.execute AttributeError: 'NoneType' object has no attribute 'execute'


I am trying to execute this peice of code:

def getServerSetting(self, setting):
    self.dbcur.execute('select value from settings where setting = ?', [str(setting)])
    rrf = self.dbr.fetchone()
    if rrf is None:
        return False
    else:
        return rrf[0]

However, I am getting this error when I run the python script:

dbcur.execute('select value from settings where setting = ?', [str(setting)])
AttributeError: 'NoneType' object has no attribute 'execute'

Solution

  • Try to write your function like this. If there are still errors, show me.

    def getServerSetting(self, setting):
    
        if not self.dbcon:
            self.dbcon = MySQLdb.connect(host='localhost', user='removed', passwd='removed', db='removed', port=21)
        self.dbcur = self.dbcon.cursor()
    
        self.dbcur.execute('select value from settings where setting = ?', [str(setting)])
        rrf = self.dbr.fetchone()
        if rrf is None:
                return False
        else:
                return rrf[0]