Python list of ints in prepared sql statement

后端 未结 3 2087
轮回少年
轮回少年 2021-01-19 05:14

My question is somewhat the same as Python list of String to SQL IN parameter but I have a list of integers. The python code I use is:

ids = [1000032, 100004         


        
相关标签:
3条回答
  • 2021-01-19 05:56

    you should cast the array of int to array of strings:

    ",".join(map(str,ids))
    
    0 讨论(0)
  • 2021-01-19 05:59

    IMO a more readable way to build a dynamic query string with placeholders using str.format

    ids = [1000032, 1000048]
    sql = 'SELECT CompNo, CompName, CompType FROM Component WHERE DeptID IN ({0})' 
    sql = sql.format(','.join('?' * len(ids)))
    cursor.execute(sql, (ids,))
    ...
    
    0 讨论(0)
  • 2021-01-19 06:16

    You cannot provide the IN-list as one argument. You need to provide the exact number of place holders in the SQL IN clause, and then provide the array to the execute method:

    ids = [1000032, 1000048]
    sql = 'SELECT CompNo, CompName, CompType FROM Component WHERE DeptID IN (' \
           + (',?' * len(ids))[1:] + ')'
    cursor.execute(sql, ids)
    
    0 讨论(0)
提交回复
热议问题