SQL Server Database Connection with pyodbc

  • Share this:

Code introduction


This function uses the pyodbc library to connect to a SQL Server database. It takes the server name, database name, username, and password as parameters and returns a connection object.


Technology Stack : pyodbc

Code Type : Database Connection

Code Difficulty : Intermediate


                
                    
import pyodbc

def connect_to_database(server, database, username, password):
    """
    Connect to a SQL Server database using pyodbc.
    """
    try:
        connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
        conn = pyodbc.connect(connection_string)
        print("Connected to the database successfully")
        return conn
    except Exception as e:
        print(f"An error occurred: {e}")
        return None                
              
Tags: