python mysql 導出到mongodb腳本

背景:

因測試性能,需要把mysql的數據導出到mongodb中。


前提:

1、用navicat或者別的什麼mysql客戶端先把mysql的數據表導出成json格式,本人用的是navicat。

2、利用mongodb的mongoimport工具。


代碼:

#coding=utf-8
import os
import json
import subprocess 


if __name__ == "__main__":
    listfile=os.listdir('.')
    for file in listfile:
        print '處理:'+file
        des_file = "d:/out/"+file
        tmp = "d:/out2/"+file
        without_suffix = file.split('.')[0]
        suffix = file.split('.')[-1]
        if suffix == 'py':
            continue
        in_f = open(file, 'r')
        out_f = open(des_file, 'w')
        # navicat 導出的格式有點點不大合適,需要把{recoder:[{item1},{item2}]}改成:[{item1},{item2}]格式
        for index, line in enumerate(in_f.readlines()):
            if index == 0:
                out_f.write('[\n')
                continue
            if '"RECORDS":[' in line:
                continue
            else:
                out_f.write(line)
        in_f.close()
        out_f.close()
        
        # 刪除最後一行
        with open(des_file) as f:
            lines = f.readlines()
            curr = lines[:-1]
            
        f = open(tmp, 'w')
        f.writelines(curr)
        f.close()
        
        # 執行mongodb import命令
        # -d 數據庫名  -c 數據表名 -f JSON文件
        cmd ='D:\MongoDB\bin\mongoimport -d"chanzai_dev" -c"%s"  --jsonArray --type=json --file=D:\out2\%s.json' % (without_suffix, without_suffix)
        print cmd
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)    
        


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章