繁体   English   中英

用python将3个列表插入mysql

[英]insert 3 list into mysql with python

我有 3 个这样的列表:

list_model = [2000, 2010, 2020, 1998, 2016]
list_worked = [1200, 0, 45000, 123000]
list_price = [920000, 123000, 12, 6500]

我想将它们插入到 MySQL 数据库中,描述如下:

+---------+------+------+-----+---------+-------+
| Field   | Type | Null | Key | Default | Extra |
+---------+------+------+-----+---------+-------+
| model   | int  | YES  |     | NULL    |       |
| worked  | int  | YES  |     | NULL    |       |
| price   | int  | YES  |     | NULL    |       |
+---------+------+------+-----+---------+-------+

我试着用

cursor = mydb.cursor()
cursor.execute ("INSERT INTO l90 VALUES (%i, %i, %i)" % (list_model, list_karkard, list_gheymat ))
mydb.commit()
mydb.close()

但它说“TypeError: %i format: a number is required, not list”,我不知道我该怎么做,有人可以帮助我吗?

您可以使用cursor.executemany ,使用zip创建要插入的元组列表:

cursor.executemany("INSERT INTO l90 VALUES (%i, %i, %i)",
                   [(m, w, p) for m, w, p in zip(list_model, list_worked, list_price)])

请注意,枚举您要插入的列是一种很好的做法,这有助于避免表结构更改时出现问题。 你应该写:

cursor.executemany("INSERT INTO l90 (model, worked, price) VALUES (%i, %i, %i)",
                   [(m, w, p) for m, w, p in zip(list_model, list_worked, list_price)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM