将列表序列化为SQLite

use*_*003 3 python sqlite serialization list pysqlite

我正在使用超过2900万个元素,因此认为数据库比数组更有意义.

以前我只是将一个元素一次传递给execute函数,但我相信一次将100,000个元素的数组传递给executemany函数会更有效.

我将我的180多行代码缩短为这个简短的测试用例:

import sqlite3

if __name__ == '__main__':
    connection = sqlite3.connect('array.db')
    cursor = connection.cursor()
    cursor.execute("create table array (word text);")
    cursor.executemany("insert into array values (?)", [u'usa', u'sharp', u'rise', u'seen', u'in', u'cd', u'bootlegs', u'sharp', u'rise', u'seen', u'in', u'cd', u'bootlegs', u'los', u'angeles'])
    connection.commit()
    cursor.execute("select * from array;")
    print cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

输出:

Traceback (most recent call last):
        cursor.executemany("insert into array values (?)", [u'usa', u'sharp', u'rise', u'seen', u'in', u'cd', u'bootlegs', u'sharp', u'rise', u'seen', u'in', u'cd', u'bootlegs', u'los', u'angeles'])
    sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

ber*_*nie 6

使用时,.executemany()您必须提供一系列元组(或列表).
所以你需要做的就是将每个单词包装成一个元组(或列表).
例:

cursor.executemany("insert into array values (?)", 
                   [(u'usa',), (u'sharp',), (u'rise',)])
Run Code Online (Sandbox Code Playgroud)

(如果上面的内容不清楚,第二个参数现在是一个元素元组的列表.)


当你考虑如何.execute()工作时,这种行为是有道理的,因为.execute()还要求参数在元组(或列表)中.
所以这不起作用:

cursor.execute("insert into array values (?)", some_word)
Run Code Online (Sandbox Code Playgroud)

但这样做:

cursor.execute("insert into array values (?)", (some_word,))
Run Code Online (Sandbox Code Playgroud)