pythonmysql-pythonmysql-connectorfetchall

How to only take 1 value in one row in fetchall()


Is there any way to take 1 value in fetchall() without displaying the other values?

import mysql.connector
import hashlib

#connect to database
cnx = mysql.connector.connect(
    host = '127.0.0.1',
    user = 'root',
    password = 'Francislaon@1406',
    database = 'useracc'
)
cr = cnx.cursor()
result = ('')

#verify connection
if cnx.is_connected():
    print('\n            /---------------------/')
    print('           /                     /')
    print('          /      Connected      /')
    print('         /---------------------/')
else:
     print('\n            /---------------------/')
     print('           /                     /')
     print('          /        FAILED       /')
     print('         /---------------------/')
    
#welcomes the user
def welcome():
    print('\n\n            /------------------------/')
    print('           /                        /')
    print('          /         WELCOME        /')
    print('         /------------------------/')
    print('\n   /----------------/    /--------------/')
    print('  /     SIGN IN    /    /    SIGN UP   /')
    print(' /----------------/    /--------------/')
    print('\n    /----------------------------/')
    userin = input ('    USER RESPONSE :      ').upper()
    print('  /----------------------------/')
    if userin == 'SIGN IN':
        return signin()

#login if the user have account
def signin():
    global result
    print('\n\n\n\n            /------------------------/')
    print('           /                        /')
    print('          /         LOGIN          /')
    print('         /------------------------/')
    usernamein = input('\n\nUSERNAME : ')
    passwordin = hashlib.sha256(input('PASSWORD : ').encode()).hexdigest()
    print('\n     /--------CHECKING--------/')
    querydata = {
        'username' : usernamein,
        'password' : passwordin
    }
    cr.execute("SELECT * FROM userdata WHERE username = %(username)s AND password = %(password)s", querydata)
    result = cr.fetchall()
    if result:
        print('\n/--------LOGIN SUCCESS--------/')
    else:
        print('\n/--------LOGIN FAILED--------/')
        return welcome()

        
    
    
    
welcome()
print(result)

I only want to take the dummy value in the output seen in the image:

I actually did nothing because I don't know python that much


Solution

  • You can use - result = cr.fetchall(), and then gets the first row - first_row = result[0] (if the query only returns single row)

    You can iterate over the cr.fetchall() -

    for row in result :
        # Based on your requirement you can get those values by accessing the index
        print("col1: ", row[0])   # 1
        print("col2: ", row[1])   # dummy
        print("col3: ", row[2])   # 4e52d35fcd82227deb6442dc8a50b72cb15cd10e993886a93d9718bc1afbdgea
    

    You can see the documentation here.