Python查询在SQL上卡壳

2024-03-28 21:21:25 发布

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

我正在尝试自动化每个月初运行的大型数据库进程。目前,这是通过数据库中已有的一堆存储过程来完成的。我目前的任务是通过Python的pyodbc运行这些存储过程。你知道吗

这些存储过程的棘手之处在于,我需要一次运行一次,这样它们就不会占用数据库的所有资源。因此,为了检查存储过程是否已运行,我创建了一个已更新的表,将过程开头名为“IsFinished”的标志改为False,最后改为True。你知道吗

当我再次尝试查询数据库时,问题就出现了。SQLServer中的活动监视器将我对跟踪表的查询显示为SUSPENDED,并被存储过程调用阻止。你知道吗

我甚至创建了一个新的数据库,这样我就可以独立地调用这两个数据库,以进一步确保我没有在争夺资源。。。但我仍然在争夺资源。你知道吗

我使用的是python3.6.4和pyodbc模块。这是我的密码。应该注意,connect_db_1()connect_db_2()指向两个独立的数据库。你知道吗

conn = connect_db_1()

conn.execute("{call dbo.StoredProcedure}")

conn2 = connect_db_2()

start_time = time.time()

finished = False

while finished is False:
    print("Looping")
    time.sleep(120)
    cursor = conn2.execute(
        "SELECT IsFinished from dbo.Tracking where StoredProcedureName='dbo.StoredProcedure'")
    results = cursor.fetchall()
    if results[0][0] == True:
        finished = True
    print(results)
print(f"dbo.StoredProcedure finished in {time_diff(start_time)} seconds.")
cursor.close()

编辑:添加了我的代码的净化版本。你知道吗


Tags: 数据库falsetruedbtime过程connect资源
1条回答
网友
1楼 · 发布于 2024-03-28 21:21:25

您希望在循环中关闭光标,因为您正在循环中创建新的光标。你知道吗

基本上,你是一次又一次地打开一个光标而没有关闭。你知道吗

while finished is False:
    print("Looping")
    time.sleep(120)
    cursor = conn2.execute(
        "SELECT IsFinished from dbo.Tracking where StoredProcedureName='dbo.StoredProcedure'")
    results = cursor.fetchall()
    if results[0][0] == True:
        finished = True
    print(results)
    cursor.close()
print(f"dbo.StoredProcedure finished in {time_diff(start_time)} seconds.")

相关问题 更多 >