[英]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.