python - 从python 2.7中的列表插入数据库

标签 python mysql list

假设我在列表中有列表。我希望它在数据库中插入列表项。

[['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/

相关文章:

python - 如何在python pptx中更改标题颜色

php - 我数据库中的数据不会显示

list - 如何比较haskell列表中的内容,看看它们是否部分相同?

python - 如何在Python中创建一个所有元素都相同的二维列表?

python - 如何在 Python 调度表中传递参数

python - 类型错误 : cannot concatenate 'str' and 'type' objects

python - logging.StreamHandler 中出现 UnicodeEncodeError

php - MySQL 多重连接 - 我如何显示数据? (使用 PHP)

MySQL Alter Table 使用通配符更改所有字段类型?

c++ - 在对象的 std::list 中快速搜索和删除