Connect to SQL Server Database with pyodbc

  • Share this:

Code introduction


This function connects to a SQL Server database using the pyodbc library. It requires the server name, database name, username, and password.


Technology Stack : pyodbc

Code Type : Function

Code Difficulty : Intermediate


                
                    
import pyodbc

def connect_to_database(server, database, username, password):
    """
    Connect to a database using pyodbc.
    """
    # Create the connection string
    connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
    
    # Establish the connection
    connection = pyodbc.connect(connection_string)
    
    return connection                
              
Tags: