Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例


Posted in Python onJune 09, 2018

本文实例讲述了Python实现读取SQLServer数据并插入到MongoDB数据库的方法。分享给大家供大家参考,具体如下:

# -*- coding: utf-8 -*-
import pyodbc
import os
import csv
import pymongo
from pymongo import ASCENDING, DESCENDING
from pymongo import MongoClient
import binascii
'''连接mongoDB数据库'''
client = MongoClient('10.20.4.79', 27017)
#client = MongoClient('10.20.66.106', 27017)
db_name = 'SoftADoutput'
db = client[db_name]
'''连接SqlServer数据库'''
connStr = 'DRIVER={SQL Server Native Client 11.0};SERVER=DESKTOP-44P34L6;DATABASE=Softput;UID=sa;PWD=sa'
conn = pyodbc.connect(connStr)
cursor = conn.cursor()
#########################################Channel_CovCode数据插入##########################
'''从SQLServer数据库读取Channel_CovCode数据写入到mongodb数据库中Channel_CovCode集合中'''
def InsertChannel_CovCode(cursor):
  cursor.execute("select dm, ms from channel_CovCode")
  rows = cursor.fetchall()
  i = 1
  for row in rows:#gb18030
    db.channel_CovCode.insert({'_id':i,'dm':row.dm,'ms':row.ms.decode('gbk').encode('utf-8')})
    i = i + 1
InsertChannel_CovCode(cursor)
#############################################################################################
#########################################channel_ModeCode数据插入#############################
'''从SQLServer数据库读取channel_ModeCode数据写入到mongodb数据库中channel_ModeCode集合中'''
def InsertChannel_ModeCode(cursor):
  cursor.execute("select dm, ms from channel_ModeCode")
  rows = cursor.fetchall()
  i = 1
  for row in rows:#gb18030
    db.channel_ModeCode.insert({'_id':i,'dm':row.dm,'ms':row.ms.decode('gbk').encode('utf-8')})
    i = i + 1
InsertChannel_ModeCode(cursor)
#############################################################################################
#########################################citynumb数据插入########################
'''从SQLServer数据库读取citynumb数据写入到mongodb数据库中citynumb集合中'''
def InsertCitynumb(cursor):
  cursor.execute("select t.XZQMC,t.SMC,t.CSMC,t.SSQYDM,t.CITY_E,t.AREA_E,t.PROV_E from citynumb t")
  rows = cursor.fetchall()
  i = 1
  for row in rows:
    xzqmc = row.XZQMC
    if xzqmc != None:
      xzqmc = xzqmc.decode('gbk').encode('utf-8')
    smc = row.SMC
    if smc != None:
      smc = smc.decode('gbk').encode('utf-8')
    csmc = row.CSMC
    if csmc != None:
      csmc = csmc.decode('gbk').encode('utf-8')
    db.citynumb.insert({'_id':i,'XZQMC':xzqmc,'SMC':smc,'CSMC':csmc,'SSQYDM':row.SSQYDM,'CITY_E':row.CITY_E,'AREA_E':row.AREA_E,'PROV_E':row.PROV_E})
    i = i + 1
InsertCitynumb(cursor)
##################################################################################################################
#########################################channel数据插入############################
'''从SQLServer数据库读取channel数据写入到mongodb数据库中channel集合中'''
def InsertChannel(cursor):
  cursor.execute("select pdcmc,pdemc,pdemcj,pdbm1,ssqydm,cov,sdate,mode,startTime,endTime,memo,pdtype,sflag,edate,corporation from channel")
  rows = cursor.fetchall()
  i = 1
  for r in rows:
    pdcmc = r.pdcmc
    if pdcmc != None:
      pdcmc = pdcmc.decode('gbk').encode('utf-8')
    memo = r.memo
    if memo != None:
      memo = memo.decode('gbk').encode('utf-8')
    corporation = r.corporation
    if corporation != None:
      corporation = corporation.decode('gbk').encode('utf-8')
    db.channel.insert({'_id':i,'pdcmc':pdcmc,'pdemc':r.pdemc,'pdemcj':r.pdemcj,'pdbm1':r.pdbm1,'ssqydm':r.ssqydm,'cov':r.cov,'sdate':r.sdate,'mode':r.mode,'startTime':r.startTime,'endTime':r.endTime,'memo':memo,'pdtype':r.pdtype,'sflag':r.sflag,'edate':r.edate,'corporation':corporation})
    i = i + 1
InsertChannel(cursor)
#############################################################################################
#########################################CPBZK数据插入############################
'''从SQLServer数据库读取CPBZK数据写入到mongodb数据库中CPBZK集合中'''
def InsertCPBZK(cursor):
  cursor.execute("select ZTC,EZTC,ZTC_CODE,LBDM,B_CODE,QY_CODE,IChange,cla from CPBZK")
    rows = cursor.fetchall()
    i = 1
    for r in rows:#gb18030
      ztc = r.ZTC
      if ztc != None:
        ztc = ztc.decode('gbk').encode('utf-8')
      db.CPBZK.insert({'_id':i,'ZTC':ztc,'EZTC':r.EZTC,'ZTC_CODE':r.ZTC_CODE,'LBDM':r.LBDM,'B_CODE':r.B_CODE,'QY_CODE':r.QY_CODE,'IChange':r.IChange,'cla':r.cla})
      i = i + 1
InsertCPBZK(cursor)
#############################################################################################
#########################################TVPGMCLASS数据插入##########################
'''从SQLServer数据库读取TVPGMCLASS数据写入到mongodb数据库中TVPGMCLASS集合中'''
def InsertTVPGMCLASS(cursor):
  cursor.execute("select ClassChDesc,ClassEnDesc,ClassCode,ParentCode,SortNo from TVPGMCLASS")
  rows = cursor.fetchall()
  i = 1
  for r in rows:#gb18030
    classChDesc = r.ClassChDesc
    if classChDesc != None:
      classChDesc = classChDesc.decode('gbk').encode('utf-8')
    db.TVPGMCLASS.insert({'_id':i,'ClassChDesc':classChDesc,'ClassEnDesc':r.ClassEnDesc,'ClassCode':r.ClassCode,
'ParentCode':r.ParentCode,'SortNo':r.SortNo})
    i = i + 1
InsertTVPGMCLASS(cursor)
#############################################################################################
#########################################GGBZK_DESCRIPTION数据插入###########################
'''从SQLServer数据库读取GGBZK_DESCRIPTION数据写入到mongodb数据库中GGBZK_DESCRIPTION集合中'''
def InsertGGBZK_DESCRIPTION(cursor):
  cursor.execute("select V_code,des_named,des_main,des_background,des_scene,des_words,ModifyFlag,UpdateDate from  GGBZK_DESCRIPTION")
  rows = cursor.fetchall()
  i = 1
  for r in rows:#gb18030
    name = r.des_named
    if name != None:
      name = name.decode('gbk').encode('utf-8')
    desmain = r.des_main
    if desmain != None:
      desmain = desmain.decode('gbk').encode('utf-8')
    background = r.des_background
    if background != None:
      background = background.decode('gbk').encode('utf-8')
    scene = r.des_scene
    if scene != None:
      scene = scene.decode('gbk').encode('utf-8')
    words = r.des_words
    if words != None:
      words = words.decode('gbk').encode('utf-8')
    db.GGBZK_DESCRIPTION.insert({'_id':i,'V_code':r.V_code,'des_named':name,'des_main':desmain,'des_background':background,
'des_scene':scene,'des_words':words,'ModifyFlag':r.ModifyFlag,'UpdateDate':r.UpdateDate})
    i = i + 1
InsertGGBZK_DESCRIPTION(cursor)
#########################################Z201607_027数据插入##########################
'''从SQLServer数据库读取Z201607_027数据写入到mongodb数据库中Z201607_027集合中'''
def InsertZ201607_027(cursor):
  strSql = "select PD,RQ,SHIJIAN,ENDSHIJIAN,LBDM,ZTC_CODE,V_CODE,B_CODE,QY_CODE,QUANLITY,SPECIAL,LANGUAGE,LENGTH,SLENGTH,QJM1,QJM2,QGG,HJM1,HJM2,HGG,DUAN,OSHIJIAN,JG,SORTNO,LURU,ZFILE,COST,ROWTS,COST1,COST2,COST3 from Z201607_027"
  cursor.execute(strSql)
  rows = cursor.fetchall()
  i = 1
  for r in rows:#gb18030
    cost = float(r.COST) #COST money类型
    cost1 = float(r.COST1)
    cost2 = float(r.COST2)
    cost3 = float(r.COST3)
    #先把时间戳转为字符串,然后再转为十进制数
    rowts = int(str(binascii.b2a_hex(r.ROWTS)),16)
    luru = r.LURU
    if luru != None:
      luru = luru.decode('gbk').encode('utf-8')
    vCODE = r.V_CODE
    if vCODE != None:
      vCODE = vCODE.decode('gbk').encode('utf-8')
    db.Z201607_027.insert({'_id':i,'PD':r.PD,'RQ':r.RQ,'SHIJIAN':r.SHIJIAN,'ENDSHIJIAN':r.ENDSHIJIAN,'LBDM':r.LBDM,
'ZTC_CODE':r.ZTC_CODE,'V_CODE':vCODE,'B_CODE':r.B_CODE,'QY_CODE':r.QY_CODE,'QUANLITY':r.QUANLITY,
'SPECIAL':r.SPECIAL,'LANGUAGE':r.LANGUAGE,'LENGTH':r.LENGTH,'SLENGTH':r.SLENGTH,'QJM1':r.QJM1,'QJM2':r.QJM2,'QGG':r.QGG,'HJM1':r.HJM1,'HJM2':r.HJM2,'HGG':r.HGG,'DUAN':r.DUAN,'OSHIJIAN':r.OSHIJIAN,'JG':r.JG,'SORTNO':r.SORTNO,'LURU':luru,'ZFILE':r.ZFILE,
'COST':cost,'ROWTS':rowts,'ExpandProperty':'','COST1':cost1,'COST2':cost2,'COST3':cost3})
    i = i + 1
InsertZ201607_027(cursor)
#############################################################################################

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python正则表达式修复网站文章字体不统一的解决方法
Feb 21 Python
python遍历文件夹下所有excel文件
Jan 03 Python
Python cookbook(数据结构与算法)让字典保持有序的方法
Feb 18 Python
儿童编程python入门
May 08 Python
Django Rest framework之权限的实现示例
Dec 17 Python
75条笑死人的知乎神回复,用60行代码就爬完了
May 06 Python
PyCharm+Qt Designer+PyUIC安装配置教程详解
Jun 13 Python
python设计微型小说网站(基于Django+Bootstrap框架)
Jul 08 Python
python多线程同步之文件读写控制
Feb 25 Python
python bluetooth蓝牙信息获取蓝牙设备类型的方法
Nov 29 Python
matplotlib绘制鼠标的十字光标的实现(自定义方式,官方实例)
Jan 10 Python
python自动化操作之动态验证码、滑动验证码的降噪和识别
Aug 30 Python
Python操作mongodb数据库进行模糊查询操作示例
Jun 09 #Python
python 用lambda函数替换for循环的方法
Jun 09 #Python
python dataframe常见操作方法:实现取行、列、切片、统计特征值
Jun 09 #Python
python pandas 如何替换某列的一个值
Jun 09 #Python
pandas 对series和dataframe进行排序的实例
Jun 09 #Python
python pandas库中DataFrame对行和列的操作实例讲解
Jun 09 #Python
python pandas修改列属性的方法详解
Jun 09 #Python
You might like
咖啡与牛奶
2021/03/03 冲泡冲煮
将酷狗krc歌词解析并转换为lrc歌词php源码
2014/06/20 PHP
php文件上传简单实现方法
2015/01/24 PHP
php使用递归函数实现数字累加的方法
2015/03/16 PHP
php实现html标签闭合检测与修复方法
2015/07/09 PHP
PHP的Laravel框架中使用消息队列queue及异步队列的方法
2016/03/21 PHP
可输入的下拉框
2006/06/19 Javascript
关于Ext中form移除textfield方法:hide(),setVisible(false),remove()
2010/12/02 Javascript
jquery怎样实现ajax联动框(一)
2013/03/08 Javascript
jQuery基本过滤选择器使用介绍
2013/04/18 Javascript
jquery批量设置属性readonly和disabled的方法
2014/01/24 Javascript
js面向对象之常见创建对象的几种方式(工厂模式、构造函数模式、原型模式)
2015/11/09 Javascript
深入理解angularjs过滤器
2016/05/25 Javascript
Bootstrap实现渐变顶部固定自适应导航栏
2020/08/27 Javascript
Vue-cropper 图片裁剪的基本原理及思路讲解
2018/04/17 Javascript
angularjs1.X 重构controller 的方法小结
2019/08/15 Javascript
[45:40]Ti4 冒泡赛第二天NEWBEE vs NaVi 1
2014/07/15 DOTA
Linux下将Python的Django项目部署到Apache服务器
2015/12/24 Python
Django权限机制实现代码详解
2018/02/05 Python
Django的models中on_delete参数详解
2019/07/16 Python
python随机生成库faker库api实例详解
2019/11/28 Python
python ssh 执行shell命令的示例
2020/09/29 Python
统计员岗位职责
2013/11/14 职场文书
医学生求职自荐书
2014/06/12 职场文书
机电一体化专业毕业生自荐信
2014/06/19 职场文书
2014年预备党员学习新党章思想汇报
2014/09/15 职场文书
甲乙双方合作协议书
2014/10/13 职场文书
汽车转让协议书范本
2014/12/07 职场文书
2015年司法局工作总结
2015/05/22 职场文书
运动会广播稿50字
2015/08/19 职场文书
2016年幼儿园教师政治学习心得体会
2016/01/23 职场文书
人为什么会“幸灾乐祸”?
2019/08/06 职场文书
青年人初次创业的“五不要”
2019/08/23 职场文书
Python趣味挑战之给幼儿园弟弟生成1000道算术题
2021/05/28 Python
python四种出行路线规划的实现
2021/06/23 Python
python中urllib包的网络请求教程
2022/04/19 Python