Connecting to SQL Server Database with pyodbc

  • Share this:

Code introduction


This function uses the pyodbc library to connect to a SQL Server database. 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):
    # This function connects to a SQL Server database using pyodbc
    connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
    connection = pyodbc.connect(connection_string)
    return connection                
              
Tags: