2017-05-07 78 views
0

我有一個帶SQL查詢的管道分隔文本文件。我試圖循環並執行每個查詢。當我在循環中的文件中打印查詢時,一切似乎都很好。如果我複製SSMS文字和運行時,SQL運行良好,但是當我試圖用pyodbc執行,我得到的錯誤:在文本文件中循環執行SQL查詢並執行 - pyodbc

ProgrammingError: No results. Previous SQL was not a query. 

這裏是我的代碼:

with open('C:/users/a/tria_file_by_ASLOB12.csv', 'r') as queryFile: 
    for line in queryFile: 
     fields = line.split('|') 
     print fields[0] 
     #cursor.execute(fields[0]) 
     #cursor.fetchall() 

返回:

SELECT COUNT(DISTINCT(pol_num)) In_Force_Count, sum(lmt_pol_s) Exposure 

      FROM bapu.dbo.fact_prem 

      WHERE aslob = 90 

      and CONCAT(2016,1231) between CAST(d_pol_eff AS DATE) and CAST(d_pol_exp AS DATE) 

      and cvg_state = 'WA' 

      and rpt_co_name in (SELECT Ent_Name FROM NAIC_Legal_Ent_Lookup WHERE ID = 40045) 


SELECT COUNT(DISTINCT(pol_num)) In_Force_Count, sum(lmt_pol_s) Exposure 

      FROM bapu.dbo.fact_prem 

      WHERE aslob = 90 

      and CONCAT(2016,1231) between CAST(d_pol_eff AS DATE) and CAST(d_pol_exp AS DATE) 

      and cvg_state = 'WI' 

      and rpt_co_name in (SELECT Ent_Name FROM NAIC_Legal_Ent_Lookup WHERE ID = 40045) 

我缺少什麼?

謝謝

+0

什麼是'fields [0]'的類型,你可以打印出來嗎? –

+0

我剛剛使用條件'pyodbc execute multiple statements'執行搜索。返回的第一個結果是http://stackoverflow.com/questions/38856534/execute-sql-file-with-multiple-statements-separated-by-using-pyodbc。我希望它或其他人幫助。 – toonice

回答

0

我想通了。我需要執行查詢,然後遍歷cursor.fetchall()的結果。這裏是我的代碼:

row_iterator = df.iterrows() 
_, last = row_iterator.next() # take first item from row_iterator 
resultFile = open('C:\\Users\\pathtofile\\file.csv', 'w') 

for i, row in row_iterator: 
    row1 = (int(row['LEGAL_ENTITY']), int(row['CY_YE']), 
int(row['TRIP_ASLOB']), row['CVG_ST'], int(row['Row'])) 
    row2 = (last['LEGAL_ENTITY'], last['CY_YE'], last['TRIP_ASLOB'], 
last['CVG_ST'], int(row['Row'])) 
    last = row 
    data = row1 
    query= """SELECT COUNT(DISTINCT(pol_num)) In_Force_Count, 
sum(distinct(lmt_pol_s)) Exposure 
       FROM bapu.dbo.xxx 
       WHERE aslob = {} 
       and CONCAT({},1231) between CAST(d_pol_eff AS DATE) and 
CAST(d_pol_exp AS DATE) 
       and cvg_state = '{}' 
       and rpt_co_name in (SELECT Ent_Name FROM NAIC_Legal_Ent_Lookup 
WHERE ID = {}) 
       and (cvg_desc = 'tria' or cvg_desc like '%terrorism%') 
       """.format(data[2],data[1],data[3], data[0]) 
    cursor.execute(query) 
    for row in cursor.fetchall(): 
     resultFile.write("{} {} {} {} {} {} {} \n".format(row[0], row[1], 
data[2], data[1], data[3], data[0], data[4])) 
     print row[0], row[1], data[2], data[1], data[3], data[0], data[4]