繁体   English   中英

将列表添加到sqlite数据库

[英]Add list to sqlite database

我如何将sqlite中的东西添加到已经存在的表中,这就是我到目前为止所拥有的

>>> rid
'26539249'
>>> for t in [(rid,("billy","jim"))]:
c.execute("insert into whois values (?,?)",t)

我如何添加到吉姆并创建列表? 还是有某种添加方式,使其可以具有多个值?

我会在这里猜测,但我怀疑我错了。

您不能在数据库中插入("billy", "jim")作为列。 这是故意的。 像sqlite这样的RDBMS的要点是,每个字段仅包含一个值,而不是值列表。 您无法在与其他人共享的列中间搜索'jim' ,也无法基于'jim ' 'jim表,等等。

如果确实要这样做,则必须选择某种方法将多个值转换为单个字符串,并在读取时将其转换回原值。 您可以使用json.dumps / json.loadsrepr / ast.literal_eval或其他任何合适的方法。 但是您必须自己编写额外的代码。 如果这样做,您将不会从数据库中获得任何真正的好处。 您最好只使用shelve

所以,我猜你不想这样做,你要知道你想要做的,而不是什么。

假设您的架构如下所示:

CREATE TABLE whois (Rid, Names);

您想要的是:

CREATE TABLE whois (Rid);
CREATE TABLE whois_names (Rid, Name, FOREIGN KEY(Rid) REFERENCES whois(Rid);

然后,执行插入操作:

tt = [(rid,("billy","jim"))]
for rid, names in tt:
    c.execute('INSERT INTO whois VALUES (?)', (rid,))
    for name in names:
        c.execute('INSERT INTO whois_names VALUES (?, ?)', (rid, name))

或(可能更快,但没有交错):

c.executemany('INSERT INTO whois VALUES (?)', (rid for rid, names in tt))
c.executemany('INSERT INTO whois_names VALUES (?, ?),
              (rid, name for rid, names in tt for name in names))

未经测试,但应该可以解决

conn = sqlite3.connect(db)
cur = conn.cursor()


cur.execute('''CREATE TABLE if not exists Data 
                (id integer primary key autoincrement, List)''')
cur.execute("INSERT INTO Data (id,List) values (?,?)", 
                (lid, str(map(lambda v : v, My_list) ) ))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM