首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从API导入数据并使用Python将其导出到MySQL数据库

问从API导入数据并使用Python将其导出到MySQL数据库
EN

Stack Overflow用户
提问于 2021-02-24 02:43:37
回答 1查看 1.3K关注 0票数 1

我试图从API中导入JSON数据,并使用Python将其导出到我的MySQL数据库中。我在代码中得到了这个错误:

代码语言:javascript
复制
pymysql.err.OperationalError: (1136, "Column count doesn't match value count at row 1")

因此,我查看了关于StackOverflow上有关此错误的类似文章,但我只看到程序员试图手动输入值的文章。我看到关于这一点的帖子通常认为缺少逗号或者没有指定所有的列,然后他们修复了这个问题。在我的例子中,我试图从API中导入数据,并且假设不手动声明值是什么导致问题的原因?不过,我不知道怎么解决这个问题。

这是我的代码:

代码语言:javascript
复制
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表?我是否应该以某种方式重新格式化“插入”行,以便从API端点获取值?这张图只显示了API中的数据以CSV格式显示的样子。你可以看到我从哪里得到的列名。

​

编辑:这是我的MySQL数据库中列名的图片,它们对齐的方式都与Insert语句中的相同。

​

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-24 06:56:14

因此,您必须做的是建立您的查询和您的值列表。例如:

代码语言:javascript
复制
# 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)))

上述数据将产生:

代码语言:javascript
复制
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')

这样,您将始终拥有匹配的字段数和数据值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66343958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档