Python 提供的绑定数量不正确

Python 提供的绑定数量不正确,python,sqlite,Python,Sqlite,我有这样一份清单: result1 = ['"United States"', '"China"', '"Sweden"', '"Europe"', '"Russian Federation"', '"China"'] 我想把它插入到一个表中: con.execute("INSERT INTO TableName(contry) VALUES(?)", result1) 但我有一个错误: 提供的绑定数量不正确。当前语句使用1,提供了74个 任何帮助都将不胜感激。或者,如果您需要更多代码,请告

我有这样一份清单:

result1 = ['"United States"', '"China"', '"Sweden"', '"Europe"', '"Russian Federation"', '"China"']
我想把它插入到一个表中:

con.execute("INSERT INTO TableName(contry) VALUES(?)", result1)
但我有一个错误:

提供的绑定数量不正确。当前语句使用1,提供了74个


任何帮助都将不胜感激。或者,如果您需要更多代码,请告诉我。

您编写的代码试图插入一行,并且在该行中您指定了74个值,而不是查询所需的1

此外,参数化查询的好处在于,您不需要(也不应该)引用字符串或执行任何其他操作来避免SQL注入攻击。因此,国家/地区列表中的字符串可能不应该被引用(除非出于某种原因希望它们在数据库中实际包含引号)

您可能正在寻找,而这需要一个列表列表。因此,您需要类似于:

result1 = [['United States'], ['China'], ['Sweden'], ...]
con.executemany("INSERT INTO TableName(contry) VALUES(?)", result1)
请注意,这(可能)运行74个独立的INSERT语句,而不是1个多行INSERT语句,具体取决于所使用的数据库。某些更高级的SQL框架(如)提供了更好地处理这一问题的工具,而您特定风格的数据库API也可能提供类似的工具

缺少这两个选项中的任何一个,执行多行插入的另一个选项如下:(编写得比需要的详细得多)

import itertools
def insert_many(con, table, data):
    """
    Inserts multiple rows into a table.

    This will fail horribly if data is empty or the number of 
    parameters (len(data) * len(data[0])) exceeds the limits of your
    particular DBAPI.

    :param con: Database connection or cursor
    :param table: Name of table, optionally including columns.
        e.g. 'TableName' or 'TableName(country)'
    :param data: List of lists of data elements.  All inner lists must be the same length.
    """

    # Represents enough parameters for one set of values.  (1, in your case)
    one_value = "({qmarks})".format(qmarks=", ".join("?" for _ in rows[0]))
    # Represents all sets of values  (74 copies of the above, in your case)
    all_values = ", ".join(one_value for _ in data)

    # Flattened version of your 2-dimensional array.
    # The 'list' may not be required; I'm not certain offhand if execute() will accept an iterator.
    data = list(itertools.chain(*data))

    con.execute(
        "INSERT INTO {table} VALUES {values}".format(table=table, values=values),
        data
    )

insert_many(con, "TableName(country)", [['United States'], ['China'], ['Sweden'], ...])