1

I'm writing to a db using this query with various placeholders:

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]])

Is there any optimized solution like

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

without generating an 'IndexError: list index out of range'?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    You can unpack a list: http://stackoverflow.com/questions/3480184/unpack-a-list-in-python – Nick Jun 10 '16 at 19:16
  • if you suggested something like 'cur.execute(sql_write_ord, ([order], *newTable))' doesn't works (with a single line) with psycopg2, or I'm wrong? The solution proposed by alecxe fit perfectly. – Federico Leoni Jun 10 '16 at 20:15
  • Should be `order` instead of `[order]` – Nick Jun 10 '16 at 20:23
  • cur.execute(sql_write_ord, (order,*newTable)): SyntaxError: invalid syntax and I need [order] because will be a list. But the unpack is a good idea for another situation I have. Thanks! – Federico Leoni Jun 10 '16 at 20:32

1 Answers1

1

You can just concatenate the lists:

cur.execute(sql_write_ord, [order] + newTable)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195