Python没有将mssql存储过程中的所有数据行写入CSV

2024-04-25 07:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,它将执行一个mssql存储过程,并将每一行写入CSV。它只输出SELECT语句的最后10行,对于最后一行,它只在前两列中有数据。在

# 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@email.com'
mail.Subject = 'Subject'
mail.body = ''
attachment1 = path
mail.Attachments.Add(Source=attachment1)
mail.send

Tags: csvthetopathimportclientdataserver
1条回答
网友
1楼 · 发布于 2024-04-25 07:24:36

是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)

相关问题 更多 >