Connect to SQL Server Database with pyodbc

  • Share this:

Code introduction


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


Technology Stack : pyodbc

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import pyodbc

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