Skip to content Skip to sidebar Skip to footer

Having Multiple Lists And Inserting Their Values Into Mysql

Here is my code to read from some data into MySql, the MySql table contains 4 columns, that in 2 columns I want to insert items of an array, each into a new row. I was able to ins

Solution 1:

I am not sure whether it solves your problem. But, to me it might be related to the way you are iterating. Example:

r=["2","3"]
b=["3","4","5","2"]
for x in r:
    for a in b:
        pass
    print(("insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','"+x+"','"+a+"')"))

Outputs(your current output):

insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','2','2')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','3','2')

If we change it with something this it works

r=["2","3"]
b=["3","4","5","2"]
for x in r:
    for a in b:
        print(("insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','"+x+"','"+a+"')"))

Outputs(as expected):

insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','2','3')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','2','4')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','2','5')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','2','2')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','3','3')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','3','4')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','3','5')
insert ignore into new_table (name,last,arrayeha,arrayeha_se) values ('ni','sal','3','2')

To ignore SQL injection

r=["2","3"]
b=["3","4","5","2"]
forxin r:
    forain b:
        print(("insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)",("ni",'sal',x,a)))

Outputs:

('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '2', '3'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '2', '4'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '2', '5'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '2', '2'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '3', '3'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '3', '4'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '3', '5'))
('insert ignore into new_table (name,last,arrayeha,arrayeha_se) values (?,?,?,?)', ('ni', 'sal', '3', '2'))

Post a Comment for "Having Multiple Lists And Inserting Their Values Into Mysql"