SQL IN operator using pyodbc and SQL Server

前端 未结 4 746
时光取名叫无心
时光取名叫无心 2020-12-28 19:53

I\'m using pyodbc to query to an SQL Server database

import datetime
import pyodbc    
conn = pyodbc.connect(\"Driver={SQL Server};Server=\'dbserver\',Datab         


        
4条回答
  •  灰色年华
    2020-12-28 20:30

    To expand on Larry and geographika's answers:

    ratings = ('PG-13', 'PG', 'G')
    st_dt = datetime(2010, 1, 1)
    end_dt = datetime(2010, 12, 31)
    
    placeholders = ', '.join('?' * len(ratings))
    vars = (*ratings, st_dt, end_dt)
    query = '''
        select title, director, producer
        from movies
        where rating in (%s)
           and release_dt between ? and ?
    ''' % placeholders
    
    cursor.execute(query, vars)
    

    With the placeholder, this will return a query of:

        select title, director, producer
        from movies
        where rating in (?, ?, ?)
           and release_dt between ? and ?
    

    If you pass in ratings, it'll attempt to fit all of its items into one ?. However, if we pass in *ratings, and each item in ratings will take its place in the in() clause. Thus, we pass the tuple (*ratings, st_dt, end_dt) to cursor.execute().

提交回复
热议问题