2017-07-20 11 views
0

i)DBに接続する、ii)クエリを実行する、iii)クエリの結果をcsvとして保存する、iv)出力。pymssqlを使用してCSVに書き込み、カラム名をヘッダとして使用

ファイルでヘッダーとして列名を取得できないことを除いて、すべて正常に動作します。私はそれを辿ってきましたが、私のために働く解決策を見つけることはできません。私のスクリプトは以下の通りです。すべてのヘルプは素晴らしいことだ:

import pymssql 
import csv 
import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email import encoders 
fromaddr='[email protected]' 
toaddr='[email protected]' 
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) 

答えて

2

DB-APIによると - どのPyMSSQL compliesに - あなたがここで使用することができます.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) 
+1

- あなたの助けのために多くのことを感謝します。 –

+0

大歓迎です! – bernie

+0

'for'ループの代わりに' writer.writerows(cursor) 'を使うこともできます。 – Davos

0

は次のように列の名前を取得するためにそれを介してcursorにオブジェクトとループ上.descriptionを使用してください:良好働い

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

    colNames = ','.join(colNameList) 
    print colNames 
関連する問題