-
#!/usr/local/bin/python
-
#coding=gbk
-
-
import ibm_db,xlwt,os
-
-
try:
-
conn=ibm_db.connect("DATABASE=secs;HOSTNAME=##ip##;PORT=##port##;PROTOCOL=TCPIP;UID=##user##;PWD=##password##;", "", "")
-
except:
-
print "no connection:", ibm_db.conn_errormsg()
-
else:
-
print "The connection was successful"
-
-
if conn:
-
strsql="select * from test1"
-
try:
-
stmt=ibm_db.exec_immediate(conn,strsql)
-
result=ibm_db.fetch_both(stmt)
-
-
filename = xlwt.Workbook(encoding = 'gbk')
-
sheet = filename.add_sheet('sheet1')
-
-
sheet.write(0,0,"ID")
-
sheet.write(0,1,"NAME")
-
sheet.write(0,2,"OPDATE")
-
-
i=1
-
-
while (result):
-
# print "id="+str(result[0])
-
# print "name="+result["NAME"]
-
-
sheet.write(i,0,result[0])
-
sheet.write(i,1,result["NAME"])
-
sheet.write(i,2,result[2])
-
-
result=ibm_db.fetch_both(stmt)
-
i=i+1
-
-
# print "len(result)=",len(result)
-
-
try:
-
filename.save('d:\db2test.xls')
-
except Exception as e:
-
print e
-
print "excel保存异常"
-
#print "按任意键结束"
-
#msvcrt.getch()
-
sys.exit()
-
-
-
except:
-
# ibm_db.rollback(conn)
-
print "Transaction couldn't be completed:" , ibm_db.stmt_errormsg()
-
else:
-
# ibm_db.commit(conn)
-
print "Transaction complete."
-
-
-
ibm_db.close
-
#print "按任意键结束"
-
#msvcrt.getch()
-
-
if os.path.exists(r'd:\db2test.xls'):
-
from email.mime.text import MIMEText
-
from email.mime.multipart import MIMEMultipart
-
import smtplib
-
-
#创建一个带附件的实例
-
msg = MIMEMultipart()
-
-
#构造附件
-
att1 = MIMEText(open('d:\db2test.xls', 'rb').read(), 'base64', 'gb2312')
-
att1["Content-Type"] = 'application/octet-stream'
-
#这里的filename可以任意写,写什么名字,邮件中显示什么名字
-
att1["Content-Disposition"] = 'attachment; filename="db2.xls"'
-
msg.attach(att1)
-
-
#加邮件头
-
msg['to'] = '##receiver##'
-
msg['from'] = '##sender##'
-
msg['subject'] = "##subject##"
-
server = smtplib.SMTP()
-
server.connect('smtp.xxxx.com')
-
server.login('xxx@xxx.com','##password##')
-
server.sendmail(msg['from'], msg['to'],msg.as_string())
-
server.quit()
-
print "mail send"
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/20777547/viewspace-1816321/
,如需转载,请注明出处,否则将追究法律责任。