2012-08-15 108 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