我正在尝试创建如下语句:

SELECT * FROM table WHERE provider IN ('provider1', 'provider2', ...)

但是,我在使用Django API的字符串格式时遇到了一些麻烦。这是我到目前为止的内容:
profile = request.user.get_profile()
providers = profile.provider.values_list('provider', flat=True) # [u'provider1', u'provider2']
providers = tuple[str(item) for item in providers] # ('provider1', 'provider2')

SQL = "SELECT * FROM table WHERE provider IN %s"
args = (providers,)
cursor.execute(sql,args)

DatabaseError
(1241, 'Operand should contain 1 column(s)')

最佳答案

MySQLdb有一种方法可以帮助解决这个问题:

文档



用法

# connection:  <_mysql.connection open to 'localhost' at 1008b2420>

str_value = connection.string_literal(tuple(provider))
# '(\'provider1\', \'provider2\')'

SQL = "SELECT * FROM table WHERE provider IN %s"
args = (str_value,)
cursor.execute(sql,args)

10-04 10:12