Search code examples
pythonmysqlpython-3.xpymysql

How to use multiple variables in pymysql


How can I use multiple variables in my query:

import pymysql

def get_firstname(y):


db = pymysql.connect(host="xxx.xxx.xxx.xxx", 
    user="xxxx",  
    passwd="xxxxx",     
    db="XXXXXXX")   

cur = db.cursor()

query = "SELECT first_name FROM information WHERE x = y;" 
cur.execute(query, (y))

result = str(cur.fetchone()[0])
return(result)

x = user_id
y = 1


print (get_firstname(y))

I would like to be able to change x to different variables, depending on my choice. Like user_id, last name, email etc. All columns in my database. #y is another variable which represent the value of the column in my database.

Ex1: if x is "user_id" and y is "1", then the result is the first name of the person with user_id 1.

Ex2: if x is "email" and y is "person@person.com", then the result is the first name of the person with the email person@person.com.


Solution

  • Use the below code:

    import pymysql
    
    def get_firstname(x, y):
        db = pymysql.connect(host='xxx.xxx.xxx.xxx',
            port=3306,
            user='xxxx',  
            password='xxxxxxxx',     
            db='test_db')   
    
        cur = db.cursor()
    
        query = "SELECT first_name FROM `information` WHERE %s" %(x)
        final_query = query+"=%s"
        #print(final_query)
        cur.execute(final_query, (y,))
    
        result = cur.fetchall()
        return(result)
    
    x = 'user_id'
    y = 1
    
    output = get_firstname(x,y)
    if output:
        for x in output:
            print(x)[0]
    

    Sample Inputs:

    x = 'email_id'
    y = 'xx@gmail.com'
    

    or

    x = 'user_id'
    y = 1        // Not enclosed with single quotes