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开发利器之ulipad的使用实践
Mar 16 Python
Python 专题三 字符串的基础知识
Mar 19 Python
python机器学习实战之树回归详解
Dec 20 Python
Python实现的多叉树寻找最短路径算法示例
Jul 30 Python
python之线程通过信号pyqtSignal刷新ui的方法
Jan 11 Python
Python常用爬虫代码总结方便查询
Feb 25 Python
解决Python找不到ssl模块问题 No module named _ssl的方法
Apr 29 Python
python实现翻转棋游戏(othello)
Jul 29 Python
python自动化实现登录获取图片验证码功能
Nov 20 Python
tensorflow指定CPU与GPU运算的方法实现
Apr 21 Python
python爬虫可以爬什么
Jun 16 Python
Python常用断言函数实例汇总
Nov 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
php基于PDO实现功能强大的MYSQL封装类实例
2017/02/27 PHP
通过PHP的Wrapper无缝迁移原有项目到新服务的实现方法
2020/04/02 PHP
海量经典的jQuery插件集合
2010/01/12 Javascript
Date对象格式化函数代码
2010/07/17 Javascript
JavaScript定义类或函数的几种方式小结
2011/01/09 Javascript
分享27个jQuery 表单插件集合推荐
2011/04/25 Javascript
jQuery实现长文字部分显示代码
2013/05/13 Javascript
Google官方支持的NodeJS访问API,提供后台登录授权
2014/07/29 NodeJs
iframe中子父类窗口调用JS的方法及注意事项
2015/08/25 Javascript
通过js获取上传的图片信息(临时保存路径,名称,大小)然后通过ajax传递给后端的方法
2015/10/01 Javascript
javascript实现表单验证
2016/01/29 Javascript
详解jQuery插件开发方式
2016/11/22 Javascript
JS产生随机数的用法小结
2016/12/10 Javascript
详解webpack+es6+angular1.x项目构建
2017/05/02 Javascript
浅析vue中的MVVM实现原理
2019/03/04 Javascript
ES6入门教程之Array.from()方法
2019/03/23 Javascript
JS原型和原型链原理与用法实例详解
2020/02/05 Javascript
javascript 内存模型实例详解
2020/04/18 Javascript
Python ValueError: invalid literal for int() with base 10 实用解决方法
2015/06/21 Python
Python基于matplotlib绘制栈式直方图的方法示例
2017/08/09 Python
tensorflow创建变量以及根据名称查找变量
2018/03/10 Python
解决pycharm工程启动卡住没反应的问题
2019/01/19 Python
python issubclass 和 isinstance函数
2019/07/25 Python
Python在终端通过pip安装好包以后在Pycharm中依然无法使用的问题(三种解决方案)
2020/03/10 Python
python 生成器需注意的小问题
2020/09/29 Python
h5页面背景图很长要有滚动条滑动效果的实现
2021/01/27 HTML / CSS
VICHY薇姿英国官网:全球专业敏感肌护肤领先品牌
2017/07/04 全球购物
纽约通行卡:The New York Pass(免费游览纽约90多个景点)
2017/07/29 全球购物
全球第二大家装零售商:Lowe’s
2018/01/13 全球购物
高中生校园生活自我评价
2013/09/19 职场文书
小学生红领巾广播稿
2014/01/21 职场文书
原料仓管员岗位职责
2014/04/12 职场文书
教师见习报告范文
2014/11/03 职场文书
团组织推优材料
2014/12/29 职场文书
2015质检员个人年终工作总结
2015/10/23 职场文书
MySQL安装失败的原因及解决步骤
2022/06/14 MySQL