Home > Enterprise >  Insert a Python LIST to the database with NON-LIST data
Insert a Python LIST to the database with NON-LIST data

Time:04-07

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

CodePudding user response:

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)
  • Related