You can download this code by clicking the button below.
This code is now available for download.
This function is used to connect to a SQL Server database. It accepts server address, database name, username, and password as parameters and returns a connection object.
Technology Stack : pyodbc
Code Type : The type of code
Code Difficulty : Intermediate
def connect_to_database(server, database, username, password):
import pyodbc
# Establish a connection to the database
connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
connection = pyodbc.connect(connection_string)
return connection