简体   繁体   中英

Query with a variable

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM