模块拆解

import xlwt
import psycopg2

workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('test',cell_overwrite_ok=True)  #to avoid mistake "Exception: Attempt to overwrite cell" 

def pgsql(sql):
    conn = psycopg2.connect(database="test", user="enniu", \
    password="postgres", host="127.0.0.1", port="5432")
    cur=conn.cursor()
    cur.execute(sql)
    rows=cur.fetchall()
    a=0
    for i in rows:
        worksheet.write(a, 0, label =i[0])   #row,column,value
        worksheet.write(a, 1, label = i[1])   #row,column,value
        a=a+1
    conn.commit()
    cur.close()
    conn.close()
    workbook.save("/Users/enniu/Desktop/pypgsql.xls") 

if __name__=='__main__':
    sql="select * from eryuezkqmd limit 6"
    pgsql(sql)

#执行sql语句
import psycopg2
def pgsql(sql):
    conn = psycopg2.connect(database="test", user="enniu", \
    password="postgres", host="127.0.0.1", port="5432")
    cur=conn.cursor()
    cur.execute(sql)
    rows=cur.fetchall()
    for i in rows:
        print i
    conn.commit()
    cur.close()
    conn.close()

if __name__=='__main__':
    sql="select * from eryuezkqmd limit 5"
    pgsql(sql)
#生成excel文件
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('test')   
worksheet.write(0, 0, label = 'singer')   #row,column,value
workbook.save("/Users/enniu/Desktop/pypgsql.xls") 

你可能感兴趣的:(模块拆解)