MSSQL.create_connection¶
- MSSQL.create_connection(database_name=None, mode=None)[source]¶
Create a SQLAlchemy connection to a Microsoft SQL Server database.
This method establishes and returns a connection to the specified database using either SQLAlchemy or pyodbc, depending on the specified
mode
.- Parameters:
database_name (str | None) – Name of the database to connect to; defaults to the name of the currently-connected database if
database_name=None
.mode (None | str) – Connection mode; defaults to using the existing engine if
mode=None
. Whenmode='pyodbc'
, it uses pyodbc.connect().
- Returns:
A SQLAlchemy connection or a pyodbc connection to the database.
- Return type:
sqlalchemy.engine.Connection | pyodbc.Connection
Examples:
>>> from pyhelpers.dbms import MSSQL >>> import sqlalchemy >>> mssql = MSSQL(verbose=True) Connecting <server_name>@localhost:1433/master ... Successfully. >>> db_conn = mssql.create_connection() >>> db_conn.should_close_with_result False >>> db_conn.closed False >>> res = db_conn.execute(sqlalchemy.text('SELECT 1')) >>> res.fetchall() [(1,)] >>> db_conn.closed False >>> db_conn.close() >>> db_conn.closed True