gpt4 book ai didi

python - 如何使用 Python 对 SQL IN 子句进行字符串格式化

转载 作者:太空狗 更新时间:2023-10-29 21:08:59 24 4
gpt4 key购买 nike

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

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 有一个方法可以帮助解决这个问题:

文档

string_literal(...) string_literal(obj) -- converts object obj into a SQL string literal. This means, any special SQL characters are escaped, and it is enclosed within single quotes. In other words, it performs:

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

关于python - 如何使用 Python 对 SQL IN 子句进行字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11195993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com