简体   繁体   English

需要帮助来遍历Python dict键/值并插入到SQL DB中

[英]Need help iterating through Python dict keys/values and INSERTing into SQL DB

I made a call to request data from Weight Gurus, which returns in the format of a python dictionary with keys and values of course. 我打了个电话,要求来自Weight Gurus的数据,Weight Gurus以python字典的格式返回,当然还有键和值。 I need to take the data retrieved from this call and INSERT each key/value pair as an individual row. 我需要获取从此调用中检索的数据,并将每个键/值对插入为单独的行。

So far I have managed to get the data from Weight Gurus and also establish a connection to my DB within python, but no luck with iterating through the dict to INSERT each value pair into an individual row. 到目前为止,我已经设法从Weight Gurus获取了数据,并在python中建立了与我的数据库的连接,但是遍历字典将每个值对插入到单独的行中并没有带来任何运气。


# Login and get the auth token
data = {"email": "", "password": ""}
login_response = requests.post("https://api.weightgurus.com/v3/account/login", data=data)
login_json = login_response.json()

# grab all your data
data_response = requests.get(
    "https://api.weightgurus.com/v3/operation/",
    headers={
        "Authorization": f'Bearer {login_json["accessToken"]}',
        "Accept": "application/json, text/plain, */*",
    },
)

scale_data_json = data_response.json()
for entry in scale_data_json["operations"]:
    print(entry)


import pyodbc    
server = ''
database = ''
username = ''
password = ''
driver='{ODBC Driver 13 for SQL Server}'

cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

The dictionary in question is comprised of 9 keys. 该词典由9个键组成。 Each key is a column within my table called BodyComposition. 每个键都是我表中名为BodyComposition的列。 Each key value pair should be an individual row. 每个键值对应该是单独的一行。 My table also has an increment ID field for the primary key if that makes a difference. 我的表也有一个主键增量ID字段(如果有所区别)。

Consider unpacking your collection of dictionaries into key/value tuples and then parameterize the values tuple in the loop. 考虑将字典集合解压缩为键/值元组,然后在循环中参数化值元组。 Assuming the below data structure (list of dictionaries): 假定以下数据结构(词典列表):

scale_data_json["operations"] = [{'BMI': 0, 'BodyFat': 10, 
                                  'Entrytimestamp': '2018-01-21T19:37:47.821Z', 
                                  'MuscleMass': 50, 'OperationType': 'create',
                                  'ServerTimestamp':'2018-01-21T19:37:47.821Z', 
                                  'Source':'bluetooth scale', 
                                  'Water':37, 'Weight':21},
                                 {'BMI': 0, 'BodyFat': 10, 
                                  'Entrytimestamp': '2018-01-21T19:37:47.821Z', 
                                  'MuscleMass': 50, 'OperationType': 'create',
                                  'ServerTimestamp':'2018-01-21T19:37:47.821Z', 
                                  'Source':'bluetooth scale', 
                                  'Water':37, 'Weight':21},
                                ...]

Loop through each dictionary, unpack the values with zip and then bind them in cursor.execute : 遍历每个字典,用zip解压缩值,然后将它们绑定到cursor.execute

# PREPARED STATEMENT
sql = """INSERT INTO BodyComposition (BMI, BodyFat, Entrytimestamp, 
                                      MuscleMass, OperationType, ServerTimestamp, 
                                      Source, Water, Weight) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      """

# LOOP, UNPACK, BIND PARAMS
for entry in scale_data_json["operations"]:
    keys, values = zip(*entry.items())
    cursor.execute(sql, values)
    cnxn.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM