Random Customer Info Fetch from SQL Server using pyodbc

  • Share this:

Code introduction


Fetches a random customer's information from a SQL Server database using the pyodbc library.


Technology Stack : pyodbc, SQL Server

Code Type : Database query

Code Difficulty : Intermediate


                
                    
import pyodbc
import random

def fetch_random_customer_info(connection_string):
    """
    Fetches a random customer information from a SQL Server database using pyodbc.
    """
    try:
        # Establish a connection to the database
        conn = pyodbc.connect(connection_string)
        cursor = conn.cursor()
        
        # Generate a random customer ID
        cursor.execute("SELECT MAX(CustomerID) FROM Customers")
        max_customer_id = cursor.fetchone()[0]
        random_customer_id = random.randint(1, max_customer_id)
        
        # Fetch the customer information
        cursor.execute("SELECT * FROM Customers WHERE CustomerID = ?", (random_customer_id,))
        customer_info = cursor.fetchone()
        
        # Close the connection
        cursor.close()
        conn.close()
        
        return customer_info
    except Exception as e:
        print(f"An error occurred: {e}")

# JSON representation of the code                
              
Tags: