9

我正在尝试创建如下声明:

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

6 回答 6

6

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) 
于 2012-06-25T19:46:32.387 回答
1

我特别不喜欢的另一个答案,但适用于您明显的用例:

providers = tuple[str(item) for item in providers] # ('provider1', 'provider2')
# rest of stuff...

SQL = 'SELECT * FROM table WHERE provider IN {}'.format(repr(providers))
cursor.execute(SQL)
于 2012-06-25T20:34:01.067 回答
0

在将字符串传递给游标对象执行之前,您可能应该进行字符串替换:

sql = "SELECT * FROM table WHERE provider IN (%s)" % \
        (','.join(str(x) for x in providers))
cursor.execute(sql)
于 2012-06-25T19:36:36.880 回答
0

因此,您需要输入 ID 的字符串:

some_vals = '1 3 5 76 5 4 2 5 7 8'.split() # convert to suitable type if required
SomeModel.objects.filter(provider__in=some_vals)
于 2012-06-25T19:47:07.253 回答
-1
"SELECT * FROM table WHERE provider IN ({0},{1},{2})".format(*args) #where args is list or tuple of arguments.
于 2012-06-25T19:30:12.030 回答
-2

试试这个....应该工作。

SQL = "SELECT * FROM table WHERE provider IN %s"%(providers)
exec 'cursor.execute("%s")'%(SQL)
于 2012-06-25T20:23:01.890 回答