假设我在列表中有列表。我希望它在数据库中插入列表项。
[['1', '2', '3'], ['0.2', '2.3', '4'], ['5.4', '2', '3']]
在这里你会看到主列表有三个子列表。我想要数据库第一列中的 1,0.2,5.4,数据库第二列中的 2,2.3,2 和数据库第三列中的 3,4,3。 给出了部分代码:
FILE_NAME = "mmd.txt"
list=[]
with open(FILE_NAME, 'r') as f:
lines = f.read().split('\n');
for line in lines:
list.append(line.split(','))
print list
for i in list:
print i
for j in i:
print j
print 'new line'
我可以将子列表与列表分开,我也可以将项目与子列表分开,但如何将它们分别插入到我的数据库中?请提出您的意见/建议。
最佳答案
你可以用executemany()
来解决:
cursor.executemany("""
INSERT INTO
MYTABLE
(COLUMN1, COLUMN2, COLUMN3)
VALUES
(%s, %s, %s)
""", mylist)
其中,我假设 mylist
是一个列表列表,每个列表包含 3 个项目:
[
['1', '2', '3'],
['0.2', '2.3', '4'],
['5.4', '2', '3']
]
并且不要将您的变量命名为 list
以避免隐藏内置的 list
。
关于python - 从python 2.7中的列表插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323313/