简体   繁体   中英

Add list to sqlite database

How would I add something in sqlite to an already existing table this is what I have so far

>>> 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. This is intentional. The whole point of RDBMSs like sqlite is that each field holds exactly one value, not a list of values. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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