Insert SQL with 3 arrays in the same table - PYTHON

Asked

Viewed 61 times

2

I have the following structure of INSERT to the database POSTGRES:

for first in nomes:
        for second in quantidades:
                for third in produtos:
                        cursor.execute(first,second,third,str(timestampInitial))

PROBLEM

It is entering an infinite looping, which runs several times the same value as the first loop

I would like to insert the lists nomes, quantidades e produtos and a single INSERT in the same database table, what is the correct way to perform this operation in python ?

  • How are these lists?

  • Example: names = [u'CARLOS',u'LUIS',u'JUNIOR']

  • Example: quantities = ['1','2','3']

  • Need to understand better what you need, you want to enter all values from a list for all values from the other lists ? example : 0 0 0 / 0 0 1 / 0 0 2 / 0 1 0 or you need each index of your lists to be inserted with its equivalent index of another list ? example : 0 0 0 / 1 1 1 / 2 2 2 ?

  • I need it to be like this: 0 0 0 / 1 1 1 / 2 2 the zip() method, solved the problem, thank you very much!

1 answer

2


Is not a loop infinity, but will really insert repeated because for each name on the list you go through all the quantities and for each quantity you go through all the products. Basically you will be entering all possible combinations between the values and this is not what you want.

If I understand correctly, you want to insert the first item in nomes, with the first item in quantidades and with the first item in produtos, so on. For this, there is the function zip python:

registros = zip(nomes, quantidades, produtos)

And you do not need to make a loop to insert one by one. There is the function called executemany which will execute the same SQL multiple times according to the data you provide.

Would basically:

sql = 'INSERT INTO ... VALUES (%s, %s, %s)'
cursor.executemany(sql, registros)
  • Oops, thank you very much, it was simpler than it looked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.