Python : How to insert a dictionary to a sqlite database?

后端 未结 5 940
别那么骄傲
别那么骄傲 2020-12-09 05:43

I have a sqlite database with a table with following columns :

id(int) , name(text) , dob(text)

I want to insert following dictionary to it

相关标签:
5条回答
  • 2020-12-09 06:01

    Here's a way which preserves parameter safety. (Might need polishing in the tablename department)

    def post_row(conn, tablename, rec):
        keys = ','.join(rec.keys())
        question_marks = ','.join(list('?'*len(rec)))
        values = tuple(rec.values())
        conn.execute('INSERT INTO '+tablename+' ('+keys+') VALUES ('+question_marks+')', values)
    
    row = {"id":"100","name":"xyz","dob":"12/12/12"}
    post_row(my_db, 'my_table', row)
    
    0 讨论(0)
  • 2020-12-09 06:03

    Looking at the documentation here you can add a single row:

    c.execute("INSERT INTO stocks VALUES (?,?,?)", [dict["id"], dict["name"], dict["dob"]])
    

    Or you can use a list and add multiple rows in one go:

    # Larger example that inserts many records at a time
    purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
                ]
    c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
    
    0 讨论(0)
  • 2020-12-09 06:07

    If, for example, c = conn.cursor(), and your dictionary is named dict and your table tablename, then you can write

    c.execute('insert into tablename values (?,?,?)', [dict['id'], dict['name'], dict['dob']])
    

    Which will insert the elements of the dictionary into the table as you require.

    0 讨论(0)
  • 2020-12-09 06:20

    As per Gareth‘s response, if you're using MySQLdb you can use executemany and pass a list of values which you can get directly from your dict using dict.values()

    0 讨论(0)
  • 2020-12-09 06:21

    To use dictionaries directly you can do:

    user1 = {"id":100, "name": "Rumpelstiltskin", "dob": "12/12/12"}
    c.execute("INSERT INTO users VALUES (:id, :name, :dob)", user1) 
    

    Using along with instances/models:

    class User:                                                                      
    
        def __init__(self, name, dob):                                            
            self.name = name                                                             
            self.dob = dao  
    
    u1 = User("Rumpelstiltskin", "12/12/12")
    c.execute("INSERT INTO users VALUES (:name, :dob)", u1.__dict__)
    

    id is a keyword in Python, so if you want to use it as an identifier of an instance variable I would recommend using _id (and the same as your table's primary key name).

    0 讨论(0)
提交回复
热议问题