Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法


Posted in Python onJanuary 11, 2018

本文实例讲述了Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法。分享给大家供大家参考,具体如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
 Purpose: 生成日汇总对账文件
 Created: 2015/4/27
 Modified:2015/5/1
 @author: guoyJoe
"""
#导入模块
import MySQLdb
import time
import datetime
import os
#日期
today = datetime.date.today()
yestoday = today - datetime.timedelta(days=1)
#对账日期
checkAcc_date = yestoday.strftime('%Y%m%d')
#对账文件目录
fileDir = "/u02/filesvrd/report"
#SQL语句
sqlStr1 = 'SELECT distinct pay_custid FROM dbpay.tb_pay_bill WHERE date_acct = %s'
#总笔数|成功交易笔数|成功交易金额|退货笔数|退货金额|撤销笔数|撤销金额
sqlStr2="""SELECT totalNum,succeedNum,succeedAmt,returnNum,returnAmt,revokeNum,revokeAmt
  FROM
    (SELECT count(order_id) AS totalNum
      FROM (SELECT p.order_id as order_id
        FROM dbpay.tb_pay_bill p, dbpay.tb_paybillserial q
        WHERE p.oid_billno = q.oid_billno
        AND p.paycust_accttype = 2
        AND p.Paycust_Type = 1
        AND p.stat_bill in (0, 4)
        AND q.pay_stat = 1
        AND q.col_stat = 1
        AND p.pay_custid = %s
        AND q.date_acct = %s
        UNION ALL
        SELECT p.order_id as order_id
        FROM dbpay.tb_pay_bill p, dbpay.tb_paybillserial q
        WHERE p.oid_billno = q.oid_billno
        AND p.col_accttype = 2
        AND p.col_type = 1
        AND p.stat_bill in (0, 4)
        AND q.pay_stat = 1
        AND q.col_stat = 1
        AND p.col_custid = %s
        AND q.date_acct = %s
        UNION ALL
        SELECT R.ORDER_ID AS ORDER_ID
        FROM DBPAY.TB_REFUND_BILL R, DBPAY.TB_PAYBILLSERIAL Q
        WHERE R.oid_refundno = Q.OID_BILLNO
         AND R.ORI_COL_ACCTTYPE = 2
         AND R.ORI_COL_TYPE = 1
         AND R.STAT_BILL = 2
         AND Q.PAY_STAT = 1
         AND Q.COL_STAT = 1
         AND R.ORI_COL_CUSTID = %s
         AND Q.DATE_ACCT = %s ) as total) A,
        (SELECT count(order_id) succeedNum ,sum(amt_paybill) succeedAmt
         FROM (SELECT p.order_id as order_id,
        q.amt_payserial/1000 as amt_paybill
        FROM dbpay.tb_pay_bill p, dbpay.tb_paybillserial q
        WHERE p.oid_billno = q.oid_billno
        AND p.paycust_accttype = 2
        AND p.Paycust_Type = 1
        AND p.stat_bill = '0'
        AND q.pay_stat = 1
        AND q.col_stat = 1
        AND p.pay_custid = %s
        AND q.date_acct = %s
        UNION ALL
        SELECT p.order_id as order_id,
        q.amt_payserial/1000 as amt_paybill
        FROM dbpay.tb_pay_bill p, dbpay.tb_paybillserial q
        WHERE p.oid_billno = q.oid_billno
        AND p.col_accttype = 2
        AND p.col_type = 1
        AND p.stat_bill = '0'
        AND q.pay_stat = 1
        AND q.col_stat = 1
        AND p.col_custid = %s
        AND q.date_acct = %s ) as succeed) B,
        (SELECT count(order_id) returnNum, sum(amt_paybill) returnAmt
        FROM (SELECT R.ORDER_ID AS ORDER_ID,
        Q.AMT_PAYSERIAL/1000 AS AMT_PAYBILL
        FROM DBPAY.TB_REFUND_BILL R, DBPAY.TB_PAYBILLSERIAL Q
        WHERE R.oid_refundno = Q.OID_BILLNO
         AND R.ORI_COL_ACCTTYPE = 2
         AND R.ORI_COL_TYPE = 1
         AND R.STAT_BILL = 2
         AND Q.PAY_STAT = 1
         AND Q.COL_STAT = 1
         AND R.ORI_COL_CUSTID = %s
         AND Q.DATE_ACCT = %s ) as retur) C,
         (SELECT count(order_id) revokeNum,sum(amt_paybill) revokeAmt
         FROM (SELECT p.order_id as order_id,
         q.amt_payserial/1000 as amt_paybill
         FROM dbpay.tb_pay_bill p, dbpay.tb_paybillserial q
        WHERE p.oid_billno = q.oid_billno
        AND p.paycust_accttype = 2
        AND p.Paycust_Type = 1
        AND p.stat_bill = '4'
        AND q.pay_stat = 1
        AND q.col_stat = 1
        AND p.pay_custid = %s
        AND q.date_acct = %s
        UNION ALL
        SELECT p.order_id as order_id,
        q.amt_payserial/1000 as amt_paybill
        FROM dbpay.tb_pay_bill p, dbpay.tb_paybillserial q
        WHERE p.oid_billno = q.oid_billno
        AND p.col_accttype = 2
        AND p.col_type = 1
        AND p.stat_bill = '4'
        AND q.pay_stat = 1
        AND q.col_stat = 1
        AND p.col_custid = %s
        AND q.date_acct = %s) as revok) D"""
try:
#连接MySQL数据库
  connDB= MySQLdb.connect("192.168.1.6","root","root","test" )
  connDB.select_db('test')
  curSql1 = connDB.cursor()
#查询商户
  curSql1.execute(sqlStr1,checkAcc_date)
  payCustID = curSql1.fetchall()
  if len(payCustID) < 1:
    print ('No found checkbill data,Please check the data for %s!' %checkAcc_date)
    exit(1)
  for row in payCustID:
      custid = row[0]
#创建汇总日账单文件名称
      fileName = '%s/JYMXSUM_%s_%s.csv' %(fileDir,custid,checkAcc_date)
#判断文件是否存在, 如果存在则删除文件,否则生成文件!
      if os.path.exists(fileName):
        os.remove(fileName)
      print 'The file start generating! %s' %time.strftime('%Y-%m-%d %H:%M:%S')
      print '%s' %fileName
#打开游标
      curSql2= connDB.cursor()
#执行SQL
      checkAcc_date = yestoday.strftime('%Y%m%d')
      curSql2.execute(sqlStr2,(custid,checkAcc_date,custid,checkAcc_date,custid,checkAcc_date,custid,checkAcc_date,c
ustid,checkAcc_date,custid,checkAcc_date,custid,checkAcc_date,custid,checkAcc_date))
#获取数据
      datesumpay = curSql2.fetchall()
#打开文件
      outfile = open(fileName,'w')
      for sumpay in datesumpay:
        totalNum = sumpay[0]
        succeedNum = sumpay[1]
        succeedAmt= sumpay[2]
        returnNum = sumpay[3]
        returnAmt = sumpay[4]
        revokeNum = sumpay[5]
        revokeAmt = sumpay[6]
#生成汇总日账单文件
        outfile.write('%s|%s|%s|%s|%s|%s|%s\n' %(totalNum,succeedNum,succeedAmt,returnNum,returnAmt,revokeNum,revo
keAmt))
      outfile.flush()
      curSql2.close()
  curSql1.close()
  connDB.close()
  print 'The file has been generated! %s' %time.strftime('%Y-%m-%d %H:%M:%S')
except MySQLdb.Error,err_msg:
  print "MySQL error msg:",err_msg

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

Python 相关文章推荐
python基础教程之自定义函数介绍
Aug 29 Python
Python性能优化技巧
Mar 09 Python
Python读大数据txt
Mar 28 Python
python写入并获取剪切板内容的实例
May 31 Python
Django连接数据库并实现读写分离过程解析
Nov 13 Python
详解Python 重学requests发起请求的基本方式
Feb 07 Python
python GUI库图形界面开发之PyQt5信号与槽的高级使用技巧(自定义信号与槽)详解与实例
Mar 06 Python
如何让python的运行速度得到提升
Jul 08 Python
Python scrapy爬取小说代码案例详解
Jul 09 Python
python matplotlib库的基本使用
Sep 23 Python
python request 模块详细介绍
Nov 10 Python
深度学习小工程练习之垃圾分类详解
Apr 14 Python
python+django+sql学生信息管理后台开发
Jan 11 #Python
hmac模块生成加入了密钥的消息摘要详解
Jan 11 #Python
快速了解Python中的装饰器
Jan 11 #Python
简单了解python模块概念
Jan 11 #Python
100行Python代码实现自动抢火车票(附源码)
Jan 11 #Python
python实现外卖信息管理系统
Jan 11 #Python
Python实现学生成绩管理系统
Apr 05 #Python
You might like
用缓存实现静态页面的测试
2006/12/06 PHP
phpMyAdmin 链接表的附加功能尚未激活问题的解决方法(已测)
2012/03/27 PHP
php使用正则验证中文
2016/04/06 PHP
js 处理数组重复元素示例代码
2013/12/27 Javascript
jQuery控制DIV层实现由大到小,由远及近动画变化效果
2015/10/09 Javascript
javascript实现的上下无缝滚动效果
2016/09/19 Javascript
jsTree使用记录实例
2016/12/01 Javascript
Angular+Node生成随机数的方法
2017/06/16 Javascript
Angular4学习笔记router的简单使用
2018/03/30 Javascript
Angular使用动态加载组件方法实现Dialog的示例
2018/05/11 Javascript
Vue CLI2升级至Vue CLI3的方法步骤
2019/05/20 Javascript
使用eslint和githooks统一前端风格的技巧
2020/07/29 Javascript
JavaScript实现拖动对话框效果的实现代码
2020/10/12 Javascript
[02:01]BBC DOTA2国际邀请赛每日综述:八强胜者组鏖战,中国队喜忧参半
2014/07/19 DOTA
Python简单日志处理类分享
2015/02/14 Python
python3实现磁盘空间监控
2018/06/21 Python
Python爬虫实现抓取京东店铺信息及下载图片功能示例
2018/08/07 Python
解决在pycharm中显示额外的 figure 窗口问题
2019/01/15 Python
Python中的引用和拷贝实例解析
2019/11/14 Python
Python TCP通信客户端服务端代码实例
2019/11/21 Python
用Python画小女孩放风筝的示例
2019/11/23 Python
python如何进行矩阵运算
2020/06/05 Python
Pytorch框架实现mnist手写库识别(与tensorflow对比)
2020/07/20 Python
Django-celery-beat动态添加周期性任务实现过程解析
2020/11/26 Python
Python实现京东抢秒杀功能
2021/01/25 Python
用python 绘制茎叶图和复合饼图
2021/02/26 Python
英国品牌男装折扣网站:Brown Bag
2018/03/08 全球购物
纽约香氛品牌:NEST Fragrance
2018/10/15 全球购物
毕业生求职简历的自我评价
2013/10/23 职场文书
护士的岗位职责
2013/12/04 职场文书
大学四年规划书范文
2013/12/27 职场文书
我的动漫时代的创业计划书范文
2014/01/27 职场文书
2014年文学毕业生自我鉴定
2014/04/23 职场文书
机关中层领导干部群众路线教育实践活动个人对照检查材料
2014/09/24 职场文书
中学教师个人总结
2015/02/10 职场文书
新闻报道稿范文
2015/07/23 职场文书