MSSQL.create_connection

MSSQL.create_connection(database_name=None, close_with_result=False, mode=None)

Create a SQLAlchemy connection.

Parameters
  • database_name (str or None) – name of a database, defaults to the name of the currently-connected database when database=None

  • close_with_result (bool) – parameter of the method sqlalchemy.engine.Engine.connect(), defaults to False

  • mode (None or str) – when mode=None (default), the method uses the existing engine; when mode='pyodbc' (optional), it uses pyodbc.connect()

Returns

a SQLAlchemy connection to a Microsoft SQL Server

Return type

sqlalchemy.engine.Connection or pyodbc.Connection

Examples:

>>> from pyhelpers.dbms import MSSQL

>>> mssql = MSSQL()
Connecting <server_name>@localhost:1433/master ... Successfully.

>>> db_conn = mssql.create_connection()
>>> db_conn.should_close_with_result
False
>>> db_conn.closed
False
>>> rslt = db_conn.execute('SELECT 1')
>>> rslt.fetchall()
[(1,)]
>>> db_conn.closed
False
>>> db_conn.close()
>>> db_conn.closed
True

>>> db_conn = mssql.create_connection(close_with_result=True)
>>> db_conn.should_close_with_result
True
>>> db_conn.closed
False
>>> rslt = db_conn.execute('SELECT 1')
>>> rslt.fetchall()
[(1,)]
>>> db_conn.closed
True