2012-08-15 104 views
6

我正在使用python +微軟的pwrtest utility休眠(S4)(或斷開連接)後如何與MS SQL重新連接?

我也正在使用SQLAlchemy的(ORM)與數據庫(MS SQL Server 2008 R2的)工作的一些冬眠的測試。

我連接到遠程SQL服務器,一切正常,但是在計算機進入休眠模式後(S4),sql server斷開連接(我將其視爲管理工作室的「活動監視器」)。

當我的電腦恢復休眠並繼續執行腳本時,出現錯誤「DBAPIError :(錯誤)('08S01','[08S01] [Microsoft] [ODBC SQL Server Driver]通信鏈路故障(0 )(SQLExecDirectW)')

我試圖使用pool_recycle

engine = create_engine(settings.sql_engine, echo=True, pool_recycle=1) 

不過,據我瞭解sqlalchemy沒有意識到,連接不存在了。

我也試圖用engine.dispose()並根據documentation它應該放棄目前的池:

Dispose of the connection pool used by this Engine.

A new connection pool is created immediately after the old one has been disposed. This new pool, like all SQLAlchemy connection pools, does not make any actual connections to the database until one is first requested.

但也沒有工作

如何重新連接到數據庫?

謝謝!

代碼:

#module db.py: 
from sqlalchemy.ext.declarative import declarative_base , declared_attr 
from sqlalchemy import * 
from sqlalchemy.orm import sessionmaker, relationship, backref 
from sqlalchemy.orm.exc import * 

Base = declarative_base() 

class Drive(Base): 
    __tablename__ = "drives" 

    id = Column(Integer, primary_key=True) 
    isPhysical = Column(Boolean) 
    devicePath = Column(String(100)) 
    name = Column(String(10)) 
    encrypted = Column(Boolean, default=False) 
    size = Column(BigInteger) 

    def __init__(self): 
     pass   

sql_engine = 'mssql+pyodbc://Tester:[email protected]/Automation' 
engine = create_engine(sql_engine, echo=True) 
Session = sessionmaker(bind=engine) 
Base.metadata.create_all(engine) 

實際通話:

#hibernation.py 

from db import * 
import subprocess 

command = r"pwrtest /sleep /s:4 /h:n /c:1" 

out = subprocess.check_output(command) 
# hibernation occurs 

session = Session() 

session.query(Drive).all() 

回答

3
+0

感謝。確實增加了偵聽器,但是它會對所有提交進行額外的查詢。我需要的是在特定情況之後重新建立連接的一次性事情。到目前爲止,我還沒有找到比在新引擎上再次調用'create_engine'和'sessionmaker'更好的方法:( – 2012-08-15 20:38:10

+0

我想知道是否有辦法觸發'raise exc.DisconnectionError()'這樣的事情,所以引擎 – 2012-08-15 20:40:37

+0

亞歷克斯,你有沒有找到一個好的解決方案?我有一個問題,我們的設置之一,我們懷疑網絡問題 – 2013-01-18 17:13:25