具有多个列表并将其值插入MySql

时间:2018-08-13 14:14:29

标签: mysql python-3.x

这是我的代码,用于从一些数据读取到MySql中,MySql表包含4列,我想在2列中插入一个数组项,每行插入一个新行。 我能够在MySql中插入一个列表,但是只是想知道如果我有多个列表会发生什么。这是代码:

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

这是输出:

1   ni  sa  2   2
2   ni  sa  3   2

有人可以解释为什么会这样吗?为什么我看不到第二个列表(b)的所有值?在这种情况下最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

我不确定它是否可以解决您的问题。但是,对我来说,这可能与您迭代的方式有关。示例:

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+"')"))

输出(您当前的输出):

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

如果我们对此进行更改,它将起作用

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+"')"))

输出(按预期):

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

忽略SQL注入

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

输出:

('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'))