用Python在SQLite3数据库中插入不同长度的行

7gs2gvoe  于 2022-11-15  发布在  SQLite
关注(0)|答案(1)|浏览(217)

我有一个列表列表,每个嵌套的列表都有不同的长度,最小长度为零,最大长度未确定。我试图将这些列表中的每一个都插入到SQLite3表中的单个列中,但收到错误消息“提供的绑定数不正确”。如何将这些数据放入SQLite3?

# LIST OF LISTS TO INSERT INTO DATABASE
list_of_scene_char_lists = [['HARPER', 'RORY', 'THOMAS'], ['AUGUST', 'THOMAS']]

# FUNCTION: CREATE THE CHARACTERS TABLE  # DO ONLY ONCE
def create_characters_table():
    conn = sqlite3.connect(project_db)
    c = conn.cursor()
    c.execute("""CREATE TABLE characters (
        scene_characters text
        )""")
    conn.commit()
    conn.close()
#create_characters_table()  # DO ONLY ONCE

# FUNCTION: INSERT CHARACTERS INTO CHARACTERS TABLE  # DO ONLY ONCE
def auto_characters(list_of_scene_char_lists):
    conn = sqlite3.connect(project_db)
    c = conn.cursor()
    c.executemany("INSERT INTO characters VALUES (?)", (list_of_scene_char_lists))
    conn.commit()
    conn.close()
auto_characters(list_of_scene_char_lists)  # DO ONLY ONCE

# ERROR
c.executemany("INSERT INTO characters VALUES (?)", (list_of_scene_char_lists))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.
aoyhnmkz

aoyhnmkz1#

您的子列表正在被解包,因此出现了错误。由于Sqlite没有“list”类型,您最好的选择可能是将子列表转换为逗号分隔的字符串:

list_of_scene_char_strings = [','.join(sub) for sub in list_of_scene_char_list]

相关问题