简体   繁体   English

将列表添加到sqlite数据库

[英]Add list to sqlite database

How would I add something in sqlite to an already existing table this is what I have so far 我如何将sqlite中的东西添加到已经存在的表中,这就是我到目前为止所拥有的

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

How would I add onto jim and create a list? 我如何添加到吉姆并创建列表? or is there some way to add onto it so It can have multiple values? 还是有某种添加方式,使其可以具有多个值?

I'll take a guess here, but I suspect I'm wrong. 我会在这里猜测,但我怀疑我错了。

You can't insert ("billy", "jim") as a column in the database. 您不能在数据库中插入("billy", "jim")作为列。 This is intentional. 这是故意的。 The whole point of RDBMSs like sqlite is that each field holds exactly one value, not a list of values. 像sqlite这样的RDBMS的要点是,每个字段仅包含一个值,而不是值列表。 You can't search for 'jim' in the middle of a column shared with other people, you can't join tables based on 'jim ', etc. 您无法在与其他人共享的列中间搜索'jim' ,也无法基于'jim ' 'jim表,等等。

If you really, really want to do this, you have to pick some way to convert the multiple values into a single string, and to convert them back on reading. 如果确实要这样做,则必须选择某种方法将多个值转换为单个字符串,并在读取时将其转换回原值。 You can use json.dumps / json.loads , repr / ast.literal_eval , or anything else that seems appropriate. 您可以使用json.dumps / json.loadsrepr / ast.literal_eval或其他任何合适的方法。 But you have to write the extra code yourself. 但是您必须自己编写额外的代码。 And you won't be getting any real benefit out of the database if you do so; 如果这样做,您将不会从数据库中获得任何真正的好处。 you'd be better off just using shelve . 您最好只使用shelve

So, I'm guessing you don't want to do this, and you want to know what you want to do instead. 所以,我猜你不想这样做,你要知道你想要做的,而不是什么。

Assuming your schema looks something like this: 假设您的架构如下所示:

CREATE TABLE whois (Rid, Names);

What you want is: 您想要的是:

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

And then, to do the insert: 然后,执行插入操作:

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))

Or (probably faster, but not as interleaved): 或(可能更快,但没有交错):

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))

Not tested but should do the trick 未经测试,但应该可以解决

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