2017-03-02 34 views
0

我正在研究一個將執行MS SQL存儲過程並將每行寫入CSV的腳本。它會輸出除SELECT語句的最後10行外的所有行,對於寫入的最後一行,它只有前兩列中的數據。Python不將所有數據行從MS SQL存儲過程寫入CSV

# Importing the required libaries 
import pypyodbc 
import csv 
import win32com.client as win32 
import time 

# Setting up the Connection to the SQL Server 
cnxn = pypyodbc.connect("Driver= {SQL Server Native Client 11.0};" 
        "Server=sql2012;" 
        "Database=Client;" 
        "Trusted_Connection=yes;") 

cursor = cnxn.cursor() 
data = cursor.execute("EXEC usp_rpt_QuestionFile") #Running the SP and housing the data 
headers = [tuple[0] for tuple in data.description] # Getting the field names out of the SP 
timestr = time.strftime("%Y%m%d") # Storing the current date 
path = "Y:\Client Files\Client\Perpetual\Questions\Client QuestionsTest"+timestr+".csv" # Where the file will be saved 
f = csv.writer(open(path, "wb"), delimiter=",") 
f.writerow(headers) #Writing the field names as the first row to the CSV 
for row in data: #Appending the data to the file 
    f.writerow(row) 


#Sending the email and attachment 
outlook = win32.Dispatch('outlook.application') 
mail = outlook.CreateItem(0) 
mail.To = '[email protected]' 
mail.Subject = 'Subject' 
mail.body = '' 
attachment1 = path 
mail.Attachments.Add(Source=attachment1) 
mail.send 
+0

當打印'row'屏幕或東西,做所有預期行從目前的SP返回? – heyiamt

回答

0

數據是從Y驅動器上的輸出文件丟失還是隻從電子郵件副本中丟失?如果是後者,看起來您需要關閉輸出文件,以便在將緩衝區複製到電子郵件之前刷新緩衝區。 最好的辦法是使用with聲明:

with open(path, "wb") as f: 
    wtr = csv.writer(f, delimiter=",") 
    wtr.writerow(headers) #Writing the field names as the first row to the CSV 
    wtr.writerows(data) 
+0

這是完美的。謝謝。 –

相關問題