【问题标题】:Insert List of lists in a database Python在数据库Python中插入列表列表
【发布时间】:2020-12-12 12:51:31
【问题描述】:

我正在尝试在数据库中插入列表列表,但出现此错误“ cursor.execute('INSERT INTO Test VALUES(?, ?, ?)',list2) sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用 3,提供了 200 个。” 在我的列表中有 201 个列表

import sqlite3
import csv
import pandas as pd
def Load():
    list1 = []
    comparar = []
    conexion = sqlite3.connect("Pruebas")
    cursor = conexion.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS Test ( "id" INT NOT NULL , "User" TEXT NOT NULL , "Followed" INT NOT NULL , PRIMARY KEY (id))')
    cursor.execute("SELECT * FROM Test")
    list1 = cursor.fetchall()
    #print(data)    
    data = pd.read_csv(r'J:\\Proyectos y Trabajos\\Python\\Bot Instagram Follow\\Terminado BR\\Test.csv',delimiter=';')
    tuples = [tuple(x) for x in data.values]
    
    for i in tuples:
        if i not in list1:
            list1.append(i)
    list2 = [list(elem) for elem in list1]
    
    cursor.execute("DELETE FROM Test") 
    conexion.commit() 
    cursor.execute('INSERT INTO Test VALUES(?, ?, ?)',list2)
    conexion.commit() 
    conexion.close()
Load()

【问题讨论】:

  • 试试cursor.execute('INSERT INTO Test VALUES(?, ?, ?)',(list2,)) 让我知道,但你也可以说print(list2) 并将其包含在Q中
  • VALUES(?, ?, ?) 表示您正在尝试插入三个值。 list2 是否正好有三个值?
  • 我现在收到此错误:文件“j:/Proyectos y Trabajos/Python/Bot Instagram Follow/Terminado BR/app.py”,第 23 行,在 Load cursor.execute('INSERT INTO Test VALUES(?, ?, ?)',(list2,)) sqlite3.ProgrammingError: 提供的绑定数量不正确。当前语句使用 3,并且提供了 1。
  • List2 是 201 个列表的列表,每个列表中都有 3 个值,例如 '[201, 'rodrigo_petrizzo', 0]'
  • 这不是你插入它的方式。一种方法是遍历列表并单独插入每一部分。

标签: python database list sqlite


【解决方案1】:

遍历list2并对每个子列表中的值执行插入:

for sublist in list2:
    cursor.execute('INSERT INTO Test VALUES(?, ?, ?)', sublist)
connexion.commit()

【讨论】:

  • 不应该是(sublist,)吗?
  • @CoolCloud 不,我不这么认为。 sublist, 是一个值的序列,但是你需要一个三个值的序列来匹配三个占位符标记。
  • 哦,是的,你说得有道理:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 2021-08-23
相关资源
最近更新 更多