Skip to content

Connection to SQL Database

Sumit Sarabhai edited this page Feb 17, 2025 · 17 revisions

Connecting to SQL Server Database

The connect() function simplifies creating a connection to SQL Server by returning a Connection object. Internally, it initializes and configures connection handle, processes the provided connection string, and attempts to establish a session with the target database.

The Connection class itself supports fundamental DB-API 2.0 features: you can create cursors to run SQL statements, control transactional behavior via methods like commit and rollback, and close the connection once you’re done. By default, autocommit mode is set to True, meaning all statements are committed immediately—if you need explicit transactional control, simply set setautocommit(False) and invoke commit or rollback as needed.

The connection string traditionally indicates the database server, the specific database to connect to, driver settings, and security details (e.g., Trusted Connection).

connect() Function

Purpose: Creates a new Connection object. Usage (example):

from mssql_python.db_connection import connect

conn_str = "Driver={SQL Server};Server=myserver;Database=mydb;Trusted_Connection=yes;"
connection = connect(conn_str)
Clone this wiki locally