使用 API 将数据插入到 sqlite3 数据库中 [英] Insert data into sqlite3 database with API

查看:36
本文介绍了使用 API 将数据插入到 sqlite3 数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将来自 Web API 的数据插入到我的数据库中(我在 python 3.7.2 上使用 sqlite3),但找不到任何有关如何操作的教程.到目前为止,我所有的代码是:

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

我的目标是获取每个驱动程序的名称和驱动程序编号,并将它们全部插入一个名为 Drivers 的表中.(我还使用了更多表的更多 API,但如果我弄清楚如何做一个,那么其余的应该没问题.)我想我必须做类似的事情

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

推荐答案

如 OP 中的注释部分所述,问题似乎是如何解析 API 点.

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"]

将是访问该 API 提供的所有驱动程序的问题的答案.

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.

这篇关于使用 API 将数据插入到 sqlite3 数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆