0

I have different sets of data that I want to be inserted to the database using Python.

a = 4
b = [12, 3, 4, 5, 9]
c = [9, 7, 4, 1, 3]
d = ' '

How can I INSERT all of the values of b in the database in the same column and the rows of a and c adjusting based on how many values of b are inserted.

I would like to ask on how I can make it look like this when inserted to the database.

ID quantity x emptyString
4 12 9
4 3 7
4 4 4
4 5 1
4 9 3

1 Answer 1

1

You just need to loop over your list and insert a line per value in it.

Something like this should do the job :

a = 4
b = [12, 3, 4, 5, 9]
c = ' '
for quantity in b:
     sql = f"INSERT INTO your_table VALUE ({a}, {quantity}, {c})"
     function_to_execute_request(sql)

EDIT : For multiple list

a = [4 , 5, 6, 7, 8]
b = [12, 3, 4, 5, 9]
c = ' '
for index, quantity in zip(a, b):
     sql = f"INSERT INTO your_table VALUE ({index}, {quantity}, {c})"
     function_to_execute_request(sql)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer! What if the case is I have more than 1 Python list and I need to insert all of it in the same column as well?
Guessing you want multiple list of same size where same position are the values for the same row. See the edit. (If it's not what you were looking for, please explain a bit more what you want from multiple lists because I'm unsure to understand correctly)
That worked. Thanks again. How about when there is an empty element on the list? How can I also insert that into the database?
For this, you will need to make sure your database column accept null value, then if your element is empty replace it by "NULL" in the loop.
How can I replace an empty element to "NULL" in the loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.