2017-03-02 64 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

这是完美的。谢谢。 –