import pymssql import pandas as pd # Way 1 : Using pymssql library def execute_query(sql_query, server='localhost', database='master', username='sa', password='your_password'): conn = pymssql.connect(server, username, password, database) # Establish a connection to the SQL Server database cursor = conn.cursor() # Create a cursor object to execute SQL queries cursor.execute(sql_query) # Execute the SQL query rows = cursor.fetchall() # Fetch all rows from the result set columns = [column[0] for column in cursor.description] # Get the column names from the cursor description df = pd.DataFrame(rows, columns=columns) # Create a DataFrame from the fetched rows and column names cursor.close() # Close the cursor conn.close() # Close the database connection return df # Return the DataFrame # Way 1 : Using pyodbc library import pyodbc import pandas as pd def execute_query(sql_query, server='localhost', database='master', username='sa', password='your_password'): # Create a connection string conn_str = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}' conn = pyodbc.connect(conn_str) # Establish a connection to the SQL Server database df = pd.read_sql(sql_query, conn) # Execute the query and load the results into a DataFrame conn.close() # Close the database connection return df # Return the DataFrame # Execute query result = execute_query("SELECT * FROM table_name") result.head(