Connecting to SQL Server Database with pyodbc

  • Share this:

Code introduction


This function uses the pyodbc library to connect to a SQL Server database and returns the connection object.


Technology Stack : pyodbc

Code Type : Function

Code Difficulty : Intermediate


                
                    
import pyodbc

def connect_to_database(server, database, username, password):
    """
    Connects to a SQL Server database using pyodbc.

    Args:
        server (str): The server name or IP address.
        database (str): The name of the database.
        username (str): The username for the database.
        password (str): The password for the database.

    Returns:
        pyodbc.Connection: The connection object to the database.
    """
    try:
        connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
        connection = pyodbc.connect(connection_string)
        return connection
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

# JSON representation of the function                
              
Tags: