Insert data into sqlite3 database with API

瘦欲@ 提交于 2021-01-27 19:27:24

问题


I'm trying to insert data from a web API into my database (I am using sqlite3 on python 3.7.2) and I can't find any tutorials on how do to so. So far all my code is:

import requests, sqlite3
database = sqlite3.connect("ProjectDatabase.db")
cur = database.cursor()

d = requests.get("http://ergast.com/api/f1/2019/drivers")

I'm aiming to get the names and driver numbers of each driver and insert them all into a table called Drivers. (I'm also using more APIs with more tables, but if I figure out how to do one then the rest should be fine.) I assume I have to do something like

cur.execute('''INSERT INTO Drivers VALUES(?,?), (driverName, driverNumber)
''')

but I'm struggling to figure out how to insert the data straight into the table from the website. Does anyone know how to do this? Thanks


回答1:


As stated in the comment section in the OP, the problem seemed to be how to parse the API point.

d = requests.get("http://ergast.com/api/f1/2019/drivers.json")
d = d.json()
drivers = d["MRData"]["DriverTable"]["Drivers"]

would be the answer to that question to access all drivers provided by that API.

To add the entries to the db you can use the following:

for dr in drivers:
    name = dr["familyName"]
    number = dr["permanentNumber"]
    sql = 'INSERT INTO Drivers (name,number) VALUES(?,?)'
    val = (name,number)
    cur.execute(sql,val)

with this solution you don't have to use specify the index and can directly access the parameter you're interested in.



来源:https://stackoverflow.com/questions/55258575/insert-data-into-sqlite3-database-with-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!