使用pyodbc执行SQL操作时进程挂起需手动终止,求错误排查方案
问题分析与解决办法
你的代码里有两个关键问题导致了进程挂起的情况:
1. 未提交事务
SQL Server在使用pypyodbc时,默认是手动提交事务的模式。你执行了UPDATE语句后,没有提交事务,这会让数据库一直持有相关锁资源,你的进程自然无法正常结束,必须手动终止SQL端进程才能释放锁。
解决办法:在cur.execute(qry)之后添加事务提交代码:
connection.commit()
2. 关闭游标和连接时未调用方法
你代码里的cur.close和connection.close只是引用了方法对象,并没有实际执行关闭操作。正确写法要加上括号,触发方法调用:
cur.close() connection.close()
修改后的完整代码
import sys sys.path.append ('C:/Users/xxxxx/source/repos/xxxx/env/Lib/site-packages') import pypyodbc connection = pypyodbc.connect('Driver={SQL Server};' 'Server=xxxxxxx;' 'Database=Testing;' 'uid=xxxxx;pwd=xxxxxx') cur = connection.cursor() qry = "Update Appoggio2 set ins='Ca1' where ins='Ro1'" cur.execute(qry) # 提交事务,释放数据库锁 connection.commit() # 实际调用方法关闭游标与连接 cur.close() connection.close()
另外,更稳妥的写法是使用with语句自动管理连接和游标,它会在代码块结束时自动处理事务提交和资源释放,避免手动操作遗漏的问题:
import sys sys.path.append ('C:/Users/xxxxx/source/repos/xxxx/env/Lib/site-packages') import pypyodbc conn_str = 'Driver={SQL Server};Server=xxxxxxx;Database=Testing;uid=xxxxx;pwd=xxxxxx' with pypyodbc.connect(conn_str) as connection: with connection.cursor() as cur: qry = "Update Appoggio2 set ins='Ca1' where ins='Ro1'" cur.execute(qry) # with块结束时自动提交事务并关闭资源
内容的提问来源于stack exchange,提问作者Diegoctn
相关产品推荐
相关产品推荐

