Home > Net >  Query with a variable
Query with a variable

Time:12-17

I would like to execute a query with a variable

I tried to do this but it doesn't work

def requeteDB(sql_request):
    with connection.cursor() as cursor:
        cursor.execute(sql_request)
        row = cursor.fetchall()
    return row

def queryWithVar():
    var = 'something with spaces'
    return('''
           Select col1
           From table1
           Where col2 = %s
           ''', [var])

 

queryWithVar()

('\n Select col1\n From table1\n Where col2 = %s\n ', ['something'])

requeteDB(queryWithVar())

TypeError: argument 1 must be a string or unicode object: got tuple instead

CodePudding user response:

The problem is that your function returns tuple, so you need to unpack it when provide it's result to execute method, just use * syntax:

def requeteDB(sql_request):
    with connection.cursor() as cursor:
        cursor.execute(*queryWithVar())
        row = cursor.fetchall()
    return row
  • Related