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?
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.
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.
you call close(), as documented. dispose() is not needed and in fact calling dispose() explicitly is virtually never needed for normal SQLAlchemy usage.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With