Python格式的数组列表成为字符串

时间:2017-01-12 15:59:20

标签: python python-2.7

我希望获取一个数组列表并将其附加到字符串中。

Python 2.7.10,Windows 10

列表是从mySQL表加载的,输出是:

skuArray = [('000381001238',) ('000381001238',) ('000381001238',) ('FA200513652',) ('000614400967',)]

我想要获取此列表并将其附加到单独的查询

问题:

query = "SELECT ItemLookupCode,Description, Quantity, Price, LastReceived "
query = query+"FROM Item "
query = query+"WHERE ItemLookupCode IN ("+skuArray+") " 
query = query+"ORDER BY LastReceived ASC;"

我收到错误:

TypeError: cannot concatenate 'str' and 'tuple' objects

我的猜测是我需要将字符串格式化为:

'000381001238', '000381001238', '000381001238', 'FA200513652','000614400967'

最终字符串需要阅读:

query = query+"WHERE ItemLookupCode IN ('000381001238', '000381001238', '000381001238', 'FA200513652','000614400967') "

我尝试了以下内容:

skuArray = ''.join(skuArray.split('(', 1))
skuArray = ''.join(skuArray.split(')', 1))

第二次尝试:

skus = [sku[0] for sku in skuArray]
stubs = ','.join(["'?'"]*len(skuArray))


msconn = pymssql.connect(host=r'*', user=r'*', password=r'*', database=r'*')
cur = msconn.cursor()
query ='''
SELECT ItemLookupCode,Description, Quantity, Price, LastReceived
FROM Item 
WHERE ItemLookupCode IN { sku_params }
ORDER BY LastReceived ASC;'''.format(sku_params = stubs)
cur.execute(query, params=skus)
row = cur.fetchone()
print row[3]
cur.close()
msconn.close()

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

如果要进行直接内联SQL,可以使用列表推导:

', '.join(["'{}'}.format(sku[0]) for sku in skuArray])

注意:您需要在元组之间添加逗号(基于示例)

那就是说,如果你想做一些sql,我会鼓励你用你的请求参数化?

以下是您将如何执行此操作的示例:

skuArray = [('000381001238',), ('000381001238',), ('000381001238',), ('FA200513652',), ('000614400967',)]
skus = [sku[0] for sku in skuArray]
stubs = ','.join(["'?'"]*len(skuArray))

qry = '''
SELECT ItemLookupCode,Description, Quantity, Price, LastReceived 
FROM Item 
WHERE ItemLookupCode IN ({ sku_params })
ORDER BY LastReceived ASC;'''.format(sku_params = stubs)

#assuming pyodbc connection syntax may be off
conn.execute(qry, params=skus)

为什么?

非参数化查询是一个坏主意,因为它使您容易受到sql注入,并且很容易避免。

答案 1 :(得分:1)

假设skuArray是一个列表,如下所示:

>>> skuArray = [('000381001238',), ('000381001238',), ('000381001238',), ('FA200513652',), ('000614400967',)]

您可以像这样格式化字符串:

>>> ', '.join(["'{}'".format(x[0]) for x in skuArray])
"'000381001238', '000381001238', '000381001238', 'FA200513652', '000614400967'"