将MYSQL数据库中指定字段数据批到导出存入文件

1、应用场景:数据库表名为年月日结构。根据查找内容导出特定字段的数据。

import calendar
import pymysql

def mysql_db(data):
    db_mysql = pymysql.connect(host="127.0.0.1", user="root", password='root', db='db', charset="utf8")
    cursor_db_mysql = db_mysql.cursor()
    cursor_db_mysql.execute(data)
    cursor_db_mysql.close()
    db_mysql.close()
    return cursor_db_mysql.fetchall()

def data_db():
    file_path = 'E:\\xxx\\'
    mon = 3
    day = 1
    while True:
        mon_day = calendar.monthrange(2021, mon)[1]
        if int(day) < 10:
            now_day = '0'+str(day)
            db_data = "SELECT 字段名 From 数据表_20210%s%s WHERE 字段名 LIKE 'Black%%'" % (str(mon), now_day)
            db_data_rsp = mysql_db(db_data)
        else:
            now_day = str(day)
            db_data = "SELECT 字段名 From 数据表_20210%s%s WHERE 字段名 LIKE 'Black%%'" % (str(mon), now_day)
            db_data_rsp = mysql_db(db_data)
        if db_data_rsp is not ():
            for Black_data in db_data_rsp:
                Black_data1 = Black_data[0]
                with open(file_path+str(mon)+'_'+str(day)+'.txt', 'a+') as f:
                    f.write(Black_data1)
                    f.write('\n')
                    f.close()
            day += 1
        else:
            day += 1
        if day > mon_day:
            mon += 1
            day = 1

        if mon > 6:
            break

if __name__=='__main__':
    data_db()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值