【问题标题】:Why wont my python list be inserted into my SQLITE database from a loop?为什么我的 python 列表不能从循环中插入到我的 SQLITE 数据库中?
【发布时间】:2020-12-18 10:56:21
【问题描述】:

我有一个非常混乱的时间,我想从 python 列表中将默认数据添加到我的表中。但是每次添加列表数据都会失败,但是我可以使用 for 循环添加硬编码数据我只是不明白为什么它不适用于列表数据。

这有效,并更新了数据库:

categories=["test 1","test 2","test 3","test 4"]

cur = db.cursor()
for category in categories:
    cur.execute("INSERT INTO CATEGORIES (name) VALUES ('category')")
                    
db.commit()
cur.close()

这不起作用:

categories=["test 1","test 2","test 3","test 4"]

cur = db.cursor()
for category in categories:
    cur.execute("INSERT INTO CATEGORIES (name) VALUES (?)",category)
                    
db.commit()
cur.close()

我的 CATEGORIES 表有一个设置为自动递增的 id 和一个名称列。我很困惑。需要帮助吗?

【问题讨论】:

    标签: python database sqlite sql-insert


    【解决方案1】:

    您需要将类别包装在一个 1 元组中(并且您将在查询中为 N 个参数提供一个 N 元组)。

    import sqlite3
    
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE CATEGORIES (name TEXT)")
    
    categories = ["test 1", "test 2", "test 3", "test 4"]
    print("Inserting...")
    cur = db.cursor()
    for category in categories:
        cur.execute("INSERT INTO CATEGORIES (name) VALUES (?)", (category,))
    db.commit()
    print("Retrieving...")
    for row in db.execute("SELECT * FROM CATEGORIES"):
        print(row)
    

    打印出来

    Inserting...
    Retrieving...
    ('test 1',)
    ('test 2',)
    ('test 3',)
    ('test 4',)
    

    更简洁的写法是使用executemany。

    生成器 ((cat,) for cat in categories) 在这里执行相同的元组包装。

    import sqlite3
    
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE CATEGORIES (name TEXT)")
    
    categories = ["test 1", "test 2", "test 3", "test 4"]
    print("Inserting...")
    db.executemany(
        "INSERT INTO CATEGORIES (name) VALUES (?)",
        ((cat,) for cat in categories),
    )
    db.commit()
    print("Retrieving...")
    for row in db.execute("SELECT * FROM CATEGORIES"):
        print(row)
    

    【讨论】:

    • 非常感谢您的成功,只是让我对未来的理解正确。从列表中插入时,列表是否应该是元组列表(最佳实践)?
    • 是的,因为例如INSERT INTO CATEGORIES (name, something_else) 将作为 [(name1, something1), (name2, something2), (name3, something3)] 输入——没有特殊情况只适用于单个变量。
    • 谢谢你们现在一切都很好,谢谢你们结束了我的困惑,我花了大约 24 小时在谷歌上搜索并盯着我的屏幕想知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2021-04-13
    • 2021-12-16
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多