如何解决将嵌套的Json插入MySQL表
我想将数据从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,"BMUReportedCurrent": 1.74,"operator": "xyz","notes": "l","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表中?到目前为止,下面的代码段是我尝试过的代码,但并未将数据插入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')
我们非常感谢您的帮助。预先感谢。
解决方法
这里更明显的问题是,您没有在行test
之前的任何地方设置mysqlCursor.executemany(rows,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,...)")
mysqlCursor.executemany(sql,rows)
(请注意,每列都需要%s
)
此外,您需要保证field
顺序与数据库的列顺序匹配,或者(更好的选择IMO)必须在INSERT中显式声明列名称:
INSERT INTO table Col1,Col2,Col3,...,ColN VALUES (%s,%s)")
最后,在将列表转换为字符串以及可能需要进行显式转换的日期字段之后,您可能需要工作reworks
字段。
仅此而已。希望我能有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。