循环遍历文本文件中的 SQL 查询并执行 - pyodbc

Posted

技术标签:

【中文标题】循环遍历文本文件中的 SQL 查询并执行 - pyodbc【英文标题】:Loop through SQL queries in a text file and execute - pyodbc 【发布时间】:2017-05-07 23:55:17 【问题描述】:

我有一个带有 SQL 查询的管道分隔文本文件。我正在尝试遍历并执行每个查询。当我在循环中打印文件中的查询时,一切似乎都很好。如果我复制文本并在 SSMS 中运行,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)

我错过了什么?

谢谢

【问题讨论】:

fields[0]是什么类型的,能打印出来吗? 我刚刚使用条件pyodbc execute multiple statements 进行了搜索。返回的第一个结果是***.com/questions/38856534/…。我希望它或其他其中之一有所帮助。 【参考方案1】:

我想通了。我需要执行查询,然后遍历 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]

【讨论】:

以上是关于循环遍历文本文件中的 SQL 查询并执行 - pyodbc的主要内容,如果未能解决你的问题,请参考以下文章

动态 SQL Server 查询循环遍历架构查找主键重复

使用 SQL 查询循环遍历文件夹

SQL查询遍历数据方法一 [ 临时表 + While循环]

sql查询出来的内容存入map,然后把他们遍历出来

循环遍历 Rmarkdown 中的分组 id 列并呈现 PDF

SSIS 错误:[执行 SQL 任务] 错误:执行查询