pymssql InterfaceError:连接已关闭,但仅在循环中(!)

时间:2017-02-10 18:14:46

标签: python sql-server sql-server-2008 pymssql

我正在开发一个ETL(提取,转换,加载)工具来自动化一些办公室工作。每个员工都有一个单独的数据集;抓取一个网站(员工ID为数字作为输入变量)给我一个数据集。

主要功能如下:

for emp_number in all_emp_numbers:
    #scrape html from website:
    web_element_scraper.main_function(str(emp_number)) 
    time.sleep(5)

    # take scraped html from one html file, clean it, and place the cleaned html in 
    # another file:
    web_element_cleaner.main_function('results_cache.html','detagged_markup.html')
    time.sleep(5)

    # convert html table into a set of nested lists: 
    table_values = table_converter.desired_table
    time.sleep(3)

    # upload nested lists (i.e., a "list of lists" into MS SQL Server 2008 database: 
    db_upload.main_function(str(emp_number))
    time.sleep(5)

print("ETL process completed.")

已导入所有相关模块等

我的问题在哪里开始:如果我为任何一个员工编号运行此脚本,脚本执行正常,并且值会按预期显示在MS SQL Server数据库表中。

但是,如果我有多个员工编号并且脚本必须多次运行,则第一次迭代(貌似)按预期工作 - 值成功上传到表 - 但是下一次迭代,无论是什么它是哪个员工编号,不是!

根据一些调试和测试,我发现问题仅限于SQL Server连接 - 即,对于后续迭代,我收到此错误:

pymssql.InterfaceError: Connection is closed. 

我真的不知道如何解决这个问题,特别是因为连接在第一次迭代时工作得很好。

已编辑添加:以下是db_upload.py模块:

import pymssql
import credentials_page
import table_converter
import time

db_connect = pymssql.connect(
    server = credentials_page.database_server,
    user = credentials_page.database_username,
    password = credentials_page.database_password,
    database = credentials_page.database_name
    )

def main_function(emp_id):
    my_cursor = db_connect.cursor()
    data_table = table_converter.desired_table
    # adjust date format:
    for data_row in data_table:
        data_row[0] = data_row[0][:26]
        data_row.append(emp_id)
    for individual_line in data_table:
        my_cursor.execute("INSERT INTO [db_table_name] VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", tuple(individual_line))
        db_connect.commit()
    time.sleep(3)
    db_connect.close()
    time.sleep(2)
    print("Data uploaded.")

1 个答案:

答案 0 :(得分:3)

你无法提交多条记录的原因是因为在你的函数中你正在调用.close()函数,它会关闭连接并要求你在函数内部运行connect,就像你现在的结构一样导入函数时,它只被调用一次。

请参阅pymssql here

中的相关文档