Search code examples
pythonmysqldictionarypymysql

Errors with dictionary in pymysql


I get the following error:

if 'ShazK01' in LogRef.values():
AttributeError: 'list' object has no attribute 'values'

After running:

import pymysql 

db = pymysql.connect(host='localhost', ..)
cur = db.cursor() 

def getData():
     LoginInput=[]
     InputUN = ('ShazK01') 
     InputPC = ('passinput') 
     LoginInput=[InputUN, InputPC] 
     return LoginInput


def checkExistence():
     cur = db.cursor(pymysql.cursors.DictCursor)
     cur.execute("SELECT Username FROM LoginDetails") 
     LogRef = cur.fetchall() #fetch ALL login references
     print(LogRef)
     if 'ShazK01' in LogRef.values():
          print("yes")
     else:
          print("no")

LoginInput = getData()
print(LoginInput)            
print(LoginInput[0])
UNInput = LoginInput[0]
print(UNInput)
checkExistence()

I've looked at other answers and they haven't been helpful. So, any helpful advice is appreciated as I'm a beginner with using sql and python together, Thanks!


Solution

  • PyMysql's fetchall returns a list (a list of dictionaries here - because of pymysql.cursors.DictCursor). You'll have to write something like

    from itertools import chain
    it = chain.from_iterable(x.values() for x in cur.fetchall())
    print('yes' if 'ShazK01' in it else 'no')
    

    or

    print('yes' if any('ShazK01' in x.values() for x in cur.fetchall()) else 'no')