簡體   English   中英

從 API 導入數據並使用 Python 將其導出到 MySQL 數據庫

[英]Importing data from an API and exporting it into MySQL database using Python

我正在嘗試從 API 導入 JSON 數據,並使用 ZA7F5F35426B923741716 腳本將其導出到我的 MySQL 數據庫中。 我的代碼中出現此錯誤:

pymysql.err.OperationalError: (1136, "Column count doesn't match value count at row 1")

因此,我在 StackOverflow 上查看了有關此錯誤的類似文章,但我只看到了程序員試圖手動輸入值的文章。 我看到有關此的帖子通常涉及缺少逗號或未指定所有列,然后他們修復了該問題。 在我的情況下,我正在嘗試從 API 導入數據,並且我假設沒有手動說明這些值是導致問題的原因? 不知道如何解決這個問題。

這是我的代碼:

import requests
import json
import pymysql

r = requests.get('https://data.cdc.gov/resource/vbim-akqf')
package_json=r.json()

con = pymysql.connect(host = 'x.x.x.x', user = 'x', passwd = 'x', db = 'x')
cursor = con.cursor()

def validate_string(val):
    if val != None:
        if type(val) is int:
            return str(val).encode('utf-8')
        else:
            return val

for i in package_json:
    t1=[] 
    for x in i:
        xx=validate_string(i.get(x, None))
        t1.append(xx)
    cursor.execute("""Insert into covid_data (cdc_case_earliest_dt, cdc_report_dt, pos_spec_dt, onset_dt, current_status, sex, age_group, race_ethnicity_combined, hosp_yn, icu_yn, death_yn, medcond_yn) VALUES {} """ .format(tuple(t1)))
con.commit()
con.close()

我的主要問題是,如您所見,我有特定的列要填充。 我沒有指定值,因為我希望從 API 中獲取所有值。 我不知道我這樣做是否正確,但我的代碼遵循本教程: https://medium.com/@himanshu_88759/how-to-import-data-from-csv-file-and-from-apis -into-mysql-database-using-python-763fb8957acc

如何使用這些值填充 MySQL 表? 我是否應該以某種方式重新格式化“INSERT INTO”行,以便它從 API 端點獲取值? 這張圖片只是顯示了來自 API 的數據在 CSV 格式中的樣子。 你可以看到我從哪里得到列名。 在此處輸入圖像描述

編輯:這是我的 MySQL 數據庫中列名的圖片,所有對齊都與我的 Insert 語句中的列名相同。 在此處輸入圖像描述

因此,您要做的就是建立您的查詢以及您的值列表。 例如:

# some test data I made up
package_json = [
    {
        'cdc_case_earliest_dt'  : 'a', 
        'cdc_report_dt'         : 'b', 
        'pos_spec_dt'           : 'c', 
        'onset_dt'              : 'd', 
        'current_status'        : 'e', 
        'sex'                   : 'f', 
        'age_group'             : 'g', 
        'race_ethnicity_combined' : 'h',
        'hosp_yn'               : 'i', 
        'icu_yn'                : 'j', 
        'death_yn'              : 'k', 
        'medcond_yn'            : 'l'
    }
]

for i in package_json:
    # start off your query string
    query = 'Insert into covid_data ('
    t1=[]
    first_item = True
    for x in i:
        xx=validate_string(i.get(x, None))
        # append the value to the value list
        t1.append(xx)
        if not first_item:
            # add a comma and space to the query if it's not the first item
            query += ', '
        # add the field name to the query
        query += x
        # mark that it's no longer the first item
        first_item = False

    # finish off the query string
    query += ') VALUES {}'
    # and send the query
    cursor.execute(query.format(tuple(t1)))

以上數據會產生:

Insert into covid_data (cdc_case_earliest_dt, cdc_report_dt, pos_spec_dt, onset_dt, current_status, sex, age_group, race_ethnicity_combined, hosp_yn, icu_yn, death_yn, medcond_yn) VALUES ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l')

這樣,您將始終擁有匹配數量的字段和數據值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM