需要帮助遍历 Python 字典 keys/values 并插入 SQL 数据库

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

我打电话向 Weight Gurus 请求数据,returns 格式为 python 字典,当然有键和值。我需要获取从此调用中检索到的数据,并将每个 key/value 对作为单独的行插入。

到目前为止,我已经设法从 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()

有问题的词典由 9 个键组成。每个键都是我的 table 中的一个列,称为 BodyComposition。每个键值对应该是一个单独的行。我的 table 也有一个用于主键的增量 ID 字段,如果有区别的话。

考虑将您的字典集合解包为 key/value 元组,然后在循环中参数化值元组。假设以下数据结构(字典列表):

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},
                                ...]

遍历每个字典,用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()