简体   繁体   English

使用pymssql写入CSV并将列名称用作标题

[英]Use pymssql to write to CSV and use column names as headers

I have the below script for i) connecting to a DB, ii) running a query, iii) saving the results of the query as a csv and iv) emailing the output. 我有以下脚本用于i)连接到数据库,ii)运行查询,iii)将查询结果保存为csv,以及iv)通过电子邮件发送输出。

It all works fine, except I can't seem to get the column names as headers on the file. 一切正常,除了我似乎无法将列名作为文件头作为标题。 I've trawled through SO, but can't find a solution that works for me. 我已经浏览了SO,但是找不到适合我的解决方案。 My script is as follows. 我的脚本如下。 Any help would be great: 任何帮助都会很棒:

import pymssql
import csv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
fromaddr='XXXX@gmail.com'
toaddr='XXXX@gmail.com'
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "This is a test"
body = "This is still a test"
conn = pymssql.connect(server='XXXXXXXXXX.net',
               port=XXXX,
               user='XXXX',
               password='XXXX',
               database='XXXX')
cursor = conn.cursor()
query = 'Select * From Table'
cursor.execute(query)
with open("XXXXXXXX.csv","w") as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_NONNUMERIC)
    for row in cursor:
        writer.writerow(row)
msg.attach(MIMEText(body,'plain'))
filename = "XXXXXX.csv"
attachment = open("XXXXXXXXXXX.csv","rb")
from email.mime.base import MIMEBase
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= %s" % filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.office365.com',587)
server.starttls()
server.login(fromaddr,"XXXXXX")
text = msg.as_string()
server.sendmail(fromaddr,toaddr,text)

According to the DB-API -- to which PyMSSQL complies -- there is a cursor attribute called .description which you can use here. 根据PyMSSQL遵循DB-API ,有一个名为.description的游标属性,您可以在此处使用。

with open("XXXXXXXX.csv","w") as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(col[0] for col in cursor.description)
    for row in cursor:
        writer.writerow(row)

Use the .description on the cursor object to and loop through it to get the names of the column like: cursor对象上使用.description并遍历它,以获取列名,例如:

colNameList = []
for i in range(len(cursor.description)):
    desc = cursor.description[i]
    colNameList.append(desc[0])

    colNames = ','.join(colNameList)
    print colNames

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM