Insert Values from dictionary into sqlite database

后端 未结 3 2099
孤独总比滥情好
孤独总比滥情好 2021-02-06 10:40

I cannot get my head around it. I want to insert the values of a dictionary into a sqlite databse.

url = \"https://api.flickr.com/services/rest/?method=flickr.ph         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 10:46

    As written, your connector.execute() statement is missing the parameters argument.

    It should be used like this:

    connector.execute("insert into some_time values (?, ?)", ["question_mark_1", "question_mark_2"])
    

    Unless you need the dictionary for later, I would actually use a list or tuple instead:

    row = [
      data.get('id'),
      data.get('title'),
      data.get('tags'),
      data.get('latitude'),
      data.get('longitude'),
    ]
    

    Then your insert statement becomes:

    connector.execute("insert into DATAGERMANY values (NULL,?,?,?,?,?)", *row)
    

    Why these changes?

    • The NULL in the values (NULL, ...) is so the auto-incrementing primary key will work
    • The list instead of the dictionary because order is important, and dictionaries don't preserve order
    • The *row so the five-element row variable will be expanded (see here for details).
    • Lastly, you shouldn't use dict as a variable name, since that's a built-in variable in Python.

提交回复
热议问题