提供的绑定数量不正确

时间:2016-02-22 17:31:17

标签: python sqlite

我有一个这样的清单:

result1 = ['"United States"', '"China"', '"Sweden"', '"Europe"', '"Russian Federation"', '"China"']

我想将其插入表格中:

con.execute("INSERT INTO TableName(contry) VALUES(?)", result1)

但是我收到了一个错误:

  

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

非常感谢任何帮助。或者如果您需要更多代码,请告诉我。

1 个答案:

答案 0 :(得分:0)

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

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

您可能正在寻找con.executemany,它会列出一系列列表。因此,您需要以下内容:

result1 = [['United States'], ['China'], ['Sweden'], ...]
con.executemany("INSERT INTO TableName(contry) VALUES(?)", result1)

请注意,这可能会运行74个单独的INSERT语句而不是1个多行INSERT,具体取决于您使用的数据库。某些更高级别的SQL框架(如SQLAlchemy)提供了更好地处理此问题的工具,您的特定数据库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'], ...])