将JSON响应数据插入SQLITE3 dB中



我在这里阅读了其他一些类似的问题,但仍然无法解决这个问题。

IM正在使用基于我传递的硬币列表从API端点获取加密价格的烧瓶应用程序。然后,我想将每个硬币和价格存储在此sqlite db中:

drop table if exists prices;
create table prices (
  id integer primary key autoincrement,
  coin text not null,
  usd int not null
);

这是我的第一次尝试,这是我的烧瓶路线和功能。因此,在这里,我将所有数据传递到字典中,然后尝试使用" db.executemany"将其放入DB中,该db.executemany不起作用并在下面丢弃了错误。

@app.route('/coindata')
def coindata():
coins = ['BTC', 'ETH', 'XRP', 'LTC', 'BCH', 'ADA', 'XLM', 'NEO', 'IOTA', 'DASH' ]
base_url = 'https://min-api.cryptocompare.com/data/price?fsym='
connector = '&tsyms='
fiat = 'USD'
coindata = {}
db = get_db()
for coin in coins:
    endpoint = base_url+coin+connector+fiat

    with urllib.request.urlopen(endpoint) as url:
        data = json.loads(url.read().decode())
        print(data) #returns {'USD': 9769.35}
        for k,v in data.items():
                price = v

        coindata.update({coin:v})

print(coindata)

db.executemany('insert into prices (coin, usd) values (?, ?)', (coindata,))
#sqlite3.ProgrammingError: Binding 1 has no name, but you supplied a dictionary (which has only names).

所以我认为我需要在for循环中调用" db.execute",然后从我的硬币列表中提交每个硬币加上返回到DB的价格的价格,但我不确定如何实施。<<<<<<<<<<<<<<<</p>

这是我在for循环中尝试的:

with urllib.request.urlopen(endpoint) as url:
            data = json.loads(url.read().decode())
            print(data)
            db.execute('INSERT INTO prices (coin) VALUES (coin)')
            db.execute('INSERT INTO price (usd) VALUES (data[1])')

这返回以下错误:

 db.execute('INSERT INTO prices (coin) VALUES (coin)')
sqlite3.OperationalError: no such column: coin

这很奇怪,因为我的架构中有硬币设置。

我也尝试过:

db.execute('INSERT INTO prices (coin, usd) VALUES (?,?)', coin, 
                data[1])

这返回一个键错误

编辑:打印(coindata(返回:

{'IOTA': 0.7129, 'BTC': 9825.56, 'NEO': 113.64, 'DASH': 609.78, 'ADA':    0.3068, 'LTC': 190.29, 'XLM': 0.3494, 'ETH': 835.72, 'XRP': 0.8966, 'BCH':    1178.76}

在sqlite3 executemany中,将嵌套在列表中的元组

data_coin = [(value1, value2), (value3, value4), ...]

因此,您可以通过列出一个空列表并将其附加到它来利用它。

coindata = []
with urllib.request.urlopen(endpoint) as url:
    data = json.loads(url.read().decode())
    print(data) #returns {'USD': 9769.35}
    for k,v in data.items():
            price = v
            coindata.apend((coin, v))
db.executemany('insert into prices (coin, usd) values (?, ?)', coindata)

最新更新