2017-03-02 4 views
0

私はMS SQLストアドプロシージャを実行し、各行をCSVに書き込むスクリプトを作成しています。 SELECTステートメントの最後の10行を除くすべての行を出力しています。最後の行については、最初の2つの列にのみデータがあります。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

これは完璧です。ありがとう。 –

関連する問題