python 请求api获取json数据插入数据库



1:按需安装库 pymssql,requests,json

2:修改相关数据库权限

3:修改api地址并解析json插入

import pymssql
import requests
import json

host = ‘127.0.0.1’

user= ‘XXX’ # 数据库允许SQL 账号登录

password=’XXXXXX’

database = ‘XXXXXXX’
conn = pymssql.connect(host= host,user=user,password=password,database=database,charset=’utf8′,autocommit=True)
print(conn)
cursor = conn.cursor()

response = requests.get(“https://XXXXXX”)
json_data = json.loads(response.text)

for item in json_data:
temp= json_data
m=str(item)
#print(item)
#print(f”{temp[m]} “)
tempA=json.loads(json.dumps(temp[m]))
#print(len(tempA))
for item0 in tempA:
#print(item0)
tempB=json.loads(json.dumps(tempA[str(item0)]))
#print()
name=tempB[“name”]
symbol=tempB[“symbol”]
logo=tempB[“logoUrl”]
decimal=tempB[“decimals”]
anyToken=tempB[“anyToken”]
liquidity=tempB[“liquidity”]
cursor = conn.cursor()

sql = f”insert into [TABLE] values (‘{str(item)}’,'{item0}’,'{name}’,'{symbol}’,'{logo}’,'{decimal}’,'{anyToken}’,'{liquidity}’); ”

cursor.execute(sql)