Connect to SQL Server Database with pyodbc

  • Share this:

Code introduction


This function connects to a Microsoft SQL Server database using the pyodbc library. It accepts the server address, database name, username, and password as parameters.


Technology Stack : pyodbc

Code Type : Database connection function

Code Difficulty : Intermediate


                
                    
import pyodbc

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