python:mysql数据转mongodb数据脚本

在工作中遇到了需要将mysql的数据转换为mongodb的数据,该脚本基于python3.X,同时需要安装pymysql与pymongo的python库

额外功能如下:

1、增加java序列化需要的_class
2、是否使用mysql主键的功能
3、增加是否使用驼峰转换
4、增加是否使用bit(1)转Boolean

#!/usr/bin/python3
import pymysql.cursors
from pymongo import MongoClient

# 想要转换的表名
mysqlTable = "b_xxx"

# java序列化用到的类, 即_class, 若不需要,则填None
# className = "com.xw.bear.model.base.XXX"
className =None

# mongodb名称
collectionName = "B_XXX"

# 是否使用mysql的id
# isMysqlId = True
isMysqlId = False

# 若数据库为app_id  这种形式, 可开启该功能, 转换成 appId
# isCase = True
isCase = False

# 是否使用mysql的bit(1)转mongodb的boolean
# isMysqlBit = True
isMysqlBit = False

# 连接mongodb
client = MongoClient('mongodb://user:password@localhost:port/')
# mongodb数据库名
admin = client.admin

# mongodb集合名称
collectionList = admin.list_collection_names()

# 如果集合存在,则删除集合所有数据, 不需要可以去掉
if collectionName in collectionList: 
    print("集合已存在!")
    admin[collectionName].remove()

# 连接mysql数据库
connect = pymysql.Connect(
    host='localhost',
    port=port,
    user='user', # 账号
    passwd='passwd', # 密码
    db='datebase', # 数据库名称
    charset='utf8' # 数据库编码
)

# 设置游标类型,默认游标类型为元祖形式
# 获取游标并将游标类型设置为字典形式,以键值对的方式输出数据, 格式:  {"列名":"值"}
cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)

# 将单词转换为驼峰格式
def upperTable(str):
    strList = str.split("_")
    newStr = ''
    if strList:
        for index in range(len(strList)):
            if len(strList) <= 1 or index == 0:
                newStr += strList[index]
            else:
                newStr += strList[index].capitalize()
    return newStr


# 将bit(1)数据转为Boolean
def convertToBoolean(strName):
    if strName:
        if type(strName) == bytes:
            if str(strName) == str(b'\x00'):
                return False
            elif str(strName) == str(b'\x01'):
                return True
    return strName


# 设置将要转换的list
tempList = []
try:
    # 打印表所有数据
    cursor.execute("select * from " + mysqlTable)

    # 将mysqlTable表中所有数据以字典形式输出
    e = list(cursor.fetchall())
    if e:
        #row 为键值对列表
        for row in e:
            #增加_class值
            if className:
                # 增加键值对 键为_class, 值为类名
                row["_class"]=className
                
			 # 列名转换
	        if isCase:
	            for index in row:
	                    key = upperTable(index)
	                    row[key] = row.pop(index)
	
	        # 将bit(1)数据转为Boolean
	        if isMysqlBit:
	            for index in row:
	                if isMysqlBit:
	                    row[index] = convertToBoolean(row[index])
			
            # 使用mysql的id作为主键
            if isMysqlId:
                row["_id"] = row["id"]
                del row["id"]
            print(row)
            #添加到需要插入的列表
            tempList.append(row)


except:
    # 如果发生错误则回滚
    connect.rollback()
cursor.close()
connect.close()

print(tempList)
if tempList:
    #批量插入到mongodb
    admin[collectionName].insert(tempList)
# 存入mongodb的打印输出的数据
for collection in admin[collectionName].find():
    # print(type(collection))
    print(collection)

猜你喜欢

转载自blog.csdn.net/Little_Matches/article/details/84775933
今日推荐