【问题标题】:Insert a nested Json into MySQL table将嵌套的 Json 插入 MySQL 表
【发布时间】:2020-10-06 19:35:54
【问题描述】:

我想将 Amazon 上托管的 DocumentDb 中的数据移动到 MySQL 表中(避免重复插入,因此我使用“INSERT IGNORE INTO”)。 DocumentDb 中的数据如下所示:

   [{
    "_id": {
        "$oid": "5f0e2c96eebd1c040a42523c"
    },
    "packNumber": 324,
    "DMMMeasuredCurrent": 1.75,
    "BMUReportedCurrent": 1.76,
    "error": 0.5,
    "operator": "Abc",
    "notes": "na",
    "reworks": [],
    "createdAt": {
        "$date": 1594764438975
    },
    "updatedAt": {
        "$date": 1594764438975
    },
    "__v": 0
}, , {
    "_id": {
        "$oid": "5f7b390701476b835e4379dd"
    },
    "packNumber": 420,
    "DMMMeasuredCurrent": 1.75,
    "BMUReportedCurrent": 1.74,
    "error": 0.5,
    "operator": "xyz",
    "notes": "l",
    "reworks": [],
    "createdAt": {
        "$date": 1601911047462
    },
    "updatedAt": {
        "$date": 1601911047462
    },
    "__v": 0
}]

我在 MySql 中创建了如下表: 创建表 auxcurrents1

(
BMUReportedCurrent varchar(50),
DMMMeasuredCurrent varchar(50),
notes   varchar(500),
packNumber  varchar(50),
__v varchar(50),
createdAt   varchar(50),
updatedAt   varchar(50),
operator    varchar(50),
idno    varchar(50),
reworks varchar(50)
)

如何将我从 DocumentDb 获取的数据插入 MySQL 表?下面的代码,sn -p 是我目前尝试过的,但是没有在MySQL表里面插入数据。

    import pymongo
    import sys
    from bson.json_util import dumps, loads
    from bson import json_util
    import mysql.connector
    from mysql.connector import connection
    #import MySQLdb
    import json
    from pandas.io import sql
    from sqlalchemy import create_engine
    import pandas as pd
    from pandas.io.json import json_normalize
    
    client = pymongo.MongoClient('mongodb://user:passwrd@host:27017/?ssl=**=.pemFile
    print('DocumentDb connected')
    
    
    #Create MySQL Connection
    mysqlConnection = mysql.connector.connect(host='host',database='db', user='user', password='passwrd',port=3306)
    mysqlCursor = mysqlConnection.cursor()
    print('MySQL Connection Established')
    
    
    #Specify the database to be used
    db = client.everestdocumentdb
    col=db.auxcurrents.find()
    print('The next line will print col')
    print(json_util.dumps(col))
    
    
    #Insert Into MySQL
    rows = ("INSERT IGNORE INTO table1 VALUES(%s)")
    mysqlCursor.executemany(rows,test)
    mysqlConnection.commit()

    print('Ran the db.execute command')

非常感谢任何帮助。提前致谢。

【问题讨论】:

  • INSERT IGNORE INTO table SET ?
  • @aRvi 怎么用?你能按照我的代码修改它吗?

标签: mysql python-3.x aws-documentdb


【解决方案1】:

这里更明显的问题是你没有在mysqlCursor.executemany(rows, test)行之前的任何地方设置test

但是要记住,MySql 与 MongoDB 不同,它是一个关系数据库,因此您不能只在其上插入 JSON。您不能像 INSERT INTO myTable VALUES (myJson) 那样期望每个 JSON 字段都会填充表中的正确列。

要做你想做的,首先,你需要将你的 JSON 转换为一个字典列表,然后将它转换为一个列表列表。类似的东西:

import json

with open("a.json") as data:
    dictionary = json.load(myJsonString)

rows = []
for field in dictionary:
    rows.append((
        field["_id"]["$oid"],
        field["packNumber"],
        field["DMMMeasuredCurrent"],
        #...other columns
        field["__v"]
    ))

print(rows)

现在你可以使用

sql = ("INSERT IGNORE INTO table1 VALUES(%s, %s, %s,...)")
mysqlCursor.executemany(sql,rows)

(请注意,每列都需要%s

除此之外,您需要保证field 的顺序与数据库的列顺序相匹配,或者(更好的选择 IMO)在 INSERT 中显式声明列名:

INSERT INTO table Col1, Col2, Col3,...,ColN VALUES (%s, %s, %s,...,%s)")

最后,在将列表转换为字符串以及可能需要显式转换的日期字段后,您可能需要使用字段 reworks

就是这样。我希望我能有所帮助。

【讨论】:

  • 感谢您的详细回复。根据您的解释,我现在已经理解了逻辑。但它给出了一个错误:field["_id"]["$oid"], TypeError: 'ObjectId' object is not subscriptable.. 你能帮我解决这个问题吗?
  • 这意味着对象不是像列表那样的对象容器。你需要弄清楚field是什么类型的对象,如果它是一个预期的列表,那么看看field[“_id”]是否也是一个列表。你用过json.load 吗?
  • 是的,我使用了 json.loads
  • 我的坏@Shrads。我的例子不完整。 json.load 期望文件流,而不是字符串。我修正了我的答案以反映这一点。您也可以使用字符串代替文件,但在这种情况下,您需要使用 'json.loads'(末尾带有“s”)。
猜你喜欢
  • 2017-10-29
  • 2018-06-19
  • 2016-04-18
  • 2018-12-29
  • 2017-08-23
  • 2011-12-05
  • 2020-03-04
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多