You can download this code by clicking the button below.
This code is now available for download.
This function connects to an ODBC database using the provided server, database name, username, and password.
Technology Stack : pyodbc
Code Type : Function
Code Difficulty : Intermediate
import pyodbc
def connect_to_database(server, database, username, password):
"""
Connect to an ODBC database using the provided credentials.
Parameters:
server (str): The server name or IP address.
database (str): The name of the database.
username (str): The username for authentication.
password (str): The password for authentication.
Returns:
pyodbc.Connection: The connection object to the database.
"""
connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
connection = pyodbc.connect(connection_string)
return connection