dataworks中PYODPS2腳本數據庫查詢結果亂碼處理


 

# -*- coding: utf-8 -*-
import datetime
import sys,time
import sys
from odps import options
import smtplib
from email.header import Header
from email.mime.text import MIMEText

# 設置編碼(此設置可修復數據庫查詢結果中文亂碼的問題)
reload(sys)
sys.setdefaultencoding('utf-8')

# 第三方 SMTP 服務
# SMTP服務器
mail_host = "smtp.126.com"      
# 用戶名
mail_user = "123@126.com"    
# 授權密碼,非登錄密碼
mail_pass = "123456"         
# 發件人郵箱(最好寫全, 不然會失敗)
sender = '123@126.com'       
# 接收郵件,可設置為你的QQ郵箱或者其他郵箱
receivers = ['abc@qq.com','bcd@qq.com']   
# 郵件主題
title = '郵件標題'  
# 發送郵件方法
def sendEmail(content):
    # 內容, 格式, 編碼
    message = MIMEText(content, 'plain', 'utf-8')  
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title
    try:
        # 啟用SSL發信, 端口一般是465
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  
        # 登錄驗證
        smtpObj.login(mail_user, mail_pass)  
        # 發送
        smtpObj.sendmail(sender, receivers, message.as_string())  
        print("mail has been send successfully.")
    except smtplib.SMTPException as e:
        print(e)

# 設置ODPS參數
options.sql.settings = {'odps.sql.allow.fullscan': 'true'}
qcc_sql = """
SELECT DISTINCT * FROM 
(
    SELECT 
    case WHEN flag1=1 then '正常'
        ELSE concat(db_name,'中文亂碼測試') end as result
        FROM 
    (select 
        t2.db_name,t2.code,COUNT(1) as flag1
    from ods_com_t_organization t2 
    where t2.is_company=1 
    and t2.is_deleted=0
    AND nvl(t2.code,'')!=''
    group by t2.db_name,t2.code
    )t1 
)t3
WHERE result != '正常'
;
"""
# 查詢SQL獲取結果
resdata = []
with o.execute_sql(qcc_sql).open_reader() as reader:
    resdata = [record.values for record in reader]
# 判斷結果是否有數據,如無則正常,如有則發送郵件並報錯退出
if resdata == []:
    print("數據正常")
else:
    result = "|".join(resdata[0])
    print(result)
    sendEmail(result)
    sys.exit(-1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM