Search code examples
pythonpymysql

pymysql - is it possible to use a variable as a "Where" parameter?


This is my code:

def lookfor(var1, var2):

try:
    with connection().cursor() as cursor:
        sql = """SELECT * FROM servers WHERE %s = %s"""

        cursor.execute(sql, (var1, var2))
        result = cursor.fetchall()

        for x in result:
            print(x)
finally:
    connection().close()

lookfor("priority", "Important")

--

I get 0 results and no errors... :(

Please help, there must be a way to do this.


Solution

  • You can use string interpolation:

    with connection().cursor() as cursor:
            sql = "SELECT * FROM servers WHERE " + str(var1) + " = " + str(var2)
    
            cursor.execute(sql)
            result = cursor.fetchall()