Python 和 MySQL:传递列表/元组

Python and MySQL: passing a list / tuple

我正在 Python 中构建查询以传递给 pymysql 查询。

condition=['m']
query = "select * from table where condition in {}'.format(tuple(condition))

我坚持的部分是我想设置脚本以在 condition 可以是单个项目或多个项目的情况下工作。

在我看来,将列表转换为元组是可行的,但事实并非如此,因为: tuple(condition) returns: ('m',) ,它无法在我的 mysql 服务器上运行。

最简单的设置方法是什么,我可以将单个值或多个值发送到我在 python 中构建的查询中的 where 子句?

使用多个条件的最简单方法是为单个 'where':

使用格式字符串
fmtstr = "select * from table where condition in {} "

还有要添加的内容:

addstr = "or condition in {} "

并根据需要连接它们。

对于您的元组,您可以像使用列表一样处理其中的项目:

x = (1, 'a')
x[0] == 1  #evaluates True
x[1] == 'a'  #same

您可能必须将其作为字符串传递,让您的 sql 服务器完成剩下的工作。 你试过了吗:

query = "select * from table where condition in {}'.format(str(tuple(condition)))`

我相信这应该可以解决您的问题:

condition=['m', 'n']

def quoteWrap(path):
    return '"' + path + '"'

query = "select * from table where condition in ({})".format(','.join([quoteWrap(c) for c in condition]))
query
#select * from table where condition in ("m","n")

我还添加了 quoteWrap 函数,显然可以将字符串用引号引起来。

我能想到的另一个技巧是替换查询的最后一部分。

如果你只有一个元素,通常会出现这个问题,那就是它在末尾放置了一个不必要的逗号,就像这样('m',)

为什么不这样做:

condition = ['m']
queryString = 'SELECT o_id FROM orders WHERE o_k_id IN ' + str(tuple(condition))
queryString = queryString.replace(',)', ')')
print(queryString)

因此您的查询将如下所示:

select * from table where condition in ('m')

如果您必须将多个值传递给 where 条件,这仍然适用:

condition = ['m', 'n']
queryString = 'select * from table where condition in ' + str(tuple(condition))
queryString = queryString.replace(',)', ')')
print(queryString)

输出:

select * from table where condition in ('m', 'n')

所以我选择了不同的路线,因为这些建议要么太麻烦,要么不起作用。

对我有用的解决方案是: cond = ', '.join('"{0}"'.format(w) for w in condition)

然后查询是: select * from table where condition in ({}).格式(条件)`

这会生成一串以逗号分隔的值,每个值都用引号括起来。示例:

condition = ['baseline', 'error']
cond = ', '.join('"{0}"'.format(w) for w in condition)   
#"baseline","error"  
query = select * from table where condition in ({})`.format(cond)   
# select * from table where condition in ("baseline","error")