SQL Server Data Fetching Function

  • Share this:

Code introduction


This function connects to a SQL Server database, executes the passed query, and returns the query results.


Technology Stack : pyodbc

Code Type : Database Access Function

Code Difficulty : Intermediate


                
                    
import pyodbc

def fetch_data_from_sql_server(connection_string, query):
    """
    Connect to a SQL Server database and execute a query to fetch data.
    """
    try:
        # Establish a connection to the database
        conn = pyodbc.connect(connection_string)
        # Create a cursor object using the connection
        cursor = conn.cursor()
        # Execute the query
        cursor.execute(query)
        # Fetch all rows from the query result
        rows = cursor.fetchall()
        # Close the cursor and the connection
        cursor.close()
        conn.close()
        return rows
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

# JSON representation of the function                
              
Tags: