小编典典

如何使用Python字符串格式化SQL IN子句

sql

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

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)')

阅读 43

收藏
2021-04-07

共1个答案

小编典典

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

文件

string_literal(…)string_literal(obj)-将对象obj转换为SQL字符串文字。这意味着,所有特殊的SQL字符都被转义,并用单引号引起来。换句话说,它执行:

"'%s'" % escape_string(str(obj))

Use connection.string_literal(obj), if you use it at all.
_mysql.string_literal(obj) cannot handle character sets.

用法

# 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)
2021-04-07