Pandas
Pandas

Reputation: 75

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?

Upvotes: 6

Views: 6431

Answers (1)

Ben Thul
Ben Thul

Reputation: 32707

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.

Upvotes: 10

Related Questions