【问题标题】:psycopg2: use a list in a query without index rowspsycopg2:在没有索引行的查询中使用列表
【发布时间】:2016-06-10 19:10:35
【问题描述】:

我正在使用带有各种占位符的查询写入数据库:

sql_write_ord = '''INSERT INTO rest_order_test (date_order, pos_line_id, pos_order_id, product_name, instructions, qty,
                partner_name, status, to_wait, to_floor) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'''

order= '2016-06-10 16:36:53'
newTable = [12821, 4421, 'Crudo MD', 'Y', Decimal('1.0'), 'Mesa 10', 'A fazer', 'N', '0']

cur.execute(sql_write_ord,[order, newTable[0], newTable[1], newTable[2], newTable[3], newTable[4], newTable[5], newTable[6], newTable[7], newTable[8]])

有没有类似的优化解决方案

cur.execute(sql_write_ord, ([order, newTable]))

没有生成“IndexError: list index out of range”?

【问题讨论】:

  • 如果您建议类似 'cur.execute(sql_write_ord, ([order], *newTable))' 的内容不适用于 psycopg2(单行),还是我错了? alecxe 提出的解决方案非常适合。
  • 应该是order 而不是[order]
  • cur.execute(sql_write_ord, (order,*newTable)): SyntaxError: invalid syntax and I need [order] 因为将是一个列表。但是对于我遇到的另一种情况,解包是个好主意。谢谢!

标签: python postgresql list python-2.7 psycopg2


【解决方案1】:

您可以只连接列表:

cur.execute(sql_write_ord, [order] + newTable)

【讨论】:

  • 简洁优雅。谢谢。
猜你喜欢
  • 2014-05-30
  • 2012-02-22
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 2013-12-02
相关资源
最近更新 更多