Inserting an array into sqlite3 python

前端 未结 3 759
闹比i
闹比i 2020-12-11 11:41

I have a list/array of strings:

l = [\'jack\',\'jill\',\'bob\']

Now I need to create a table in slite3 for python using which I can insert

相关标签:
3条回答
  • 2020-12-11 11:52

    This is not the way to go. You should consider creating another table for names with foreign key to names.

    0 讨论(0)
  • 2020-12-11 12:09

    You can store an array in a single string field, if you somehow genereate a string representation of it, e.g. sing the pickle module. Then, when you read the line, you can unpickle it. Pickle converts many different complex objects (but not all) into a string, that the object can be restored of. But: that is most likely not what you want to do (you wont be able to do anything with the data in the tabel, except selecting the lines and then unpickle the array. You wont be able to search.

    If you want to have anything of varying length (or fixed length, but many instances of similiar things), you would not want to put that in a column or multiple columns. Thing vertically, not horizontally there, meaning: don't thing about columns, think about rows. For storing a vector with any amount of components, a table is a good tool.

    It is a little difficult to explain from the little detail you give, but you should think about creating a second table and putting all the names there for every row of your first table. You'd need some key in your first table, that you can use for your second table, too:

    c.execute("CREATE TABLE first_table(int id, varchar(255) text, additional fields)")
    c.execute("CREATE TABLE names_table(int id, int num, varchar(255) name)")
    

    With this you can still store whatever information you have except the names in first_table and store the array of names in names_table, just use the same id as in first_table and num to store the index positions inside the array. You can then later get back the array by doing someting like

    SELECT name FROM names_table 
    WHERE id=?
    ORDER BY num
    

    to read the array of names for any of your rows in first_table.

    That's a pretty normal way to store arrays in a DB.

    0 讨论(0)
  • 2020-12-11 12:09

    You could pickle/marshal/json your array and store it as binary/varchar/jsonfield in your database.

    Something like:

    import json
    
    names = ['jack','jill','bill']
    snames = json.dumps(names)
    c.execute("INSERT INTO nametable " + snames + ";")
    
    0 讨论(0)
提交回复
热议问题