Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Alchemy Check Connection

I created the below method to connect to SQL Server using SQL Alchemy and Pyodbc.

def getDBEngine(server, database):
    Params = urllib.quote_plus("DRIVER={SQL Server};SERVER="+server+";DATABASE="+database+";TRUSTED_CONNECTION=Yes")
    Engine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % Params)

    return Engine

I'm able to then use that engine to read and write data via methods like to_sql from pandas per the below.

def toSQL(Server, Database, Tablename):
    writeEngine= getDatabaseEngine(Server, Database)
    data.to_sql('write_Tablename',writeEngine,if_exists='append')

My question is whether there is a simple way to check the connection/ status of the engine before actually using it to read or write data. What's the easiest way?

like image 755
Pandas Avatar asked Aug 06 '17 18:08

Pandas


People also ask

Does SQLAlchemy close connection automatically?

close() method is automatically invoked at the end of the block. The Connection , is a proxy object for an actual DBAPI connection. The DBAPI connection is retrieved from the connection pool at the point at which Connection is created.

Does SQLAlchemy use connection pool?

SQLAlchemy includes several connection pool implementations which integrate with the Engine . They can also be used directly for applications that want to add pooling to an otherwise plain DBAPI approach.

How do I close a SQLAlchemy connection?

you call close(), as documented. dispose() is not needed and in fact calling dispose() explicitly is virtually never needed for normal SQLAlchemy usage.


Video Answer


1 Answers

One pattern I've seen used at multiple engagements is essentially a "is alive" check that is effectively select 1 as is_alive;. There's no data access, so it just checks where your connection is receptive to receiving commands from your application.

like image 89
Ben Thul Avatar answered Sep 20 '22 22:09

Ben Thul