【问题标题】:insert 3 list into mysql with python用python将3个列表插入mysql
【发布时间】:2020-03-25 05:45:23
【问题描述】:

我有 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” 我不知道该怎么办,谁能帮帮我?

【问题讨论】:

  • 您是要插入 5*4*4=80 条记录(所有可能的组合),还是要插入 5 条位置匹配的记录(第 5 条记录在 workedprice 因为列表大小不同)?

标签: python mysql mariadb


【解决方案1】:

您可以使用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)])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 2013-04-19
    • 2012-05-08
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多