Connecting to SQL Server and Fetching Random Column Data

  • Share this:

Code introduction


This code defines two functions: the first function is used to connect to a Microsoft SQL Server database, and the second function is used to fetch a random column value from a specified table.


Technology Stack : pyodbc

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import pyodbc
import random

def connect_to_database(server, database, username, password):
    # Connect to a Microsoft SQL Server database using pyodbc
    connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
    connection = pyodbc.connect(connection_string)
    return connection

def fetch_random_column_data(connection, table_name):
    # Fetch a random column from a table in a Microsoft SQL Server database
    cursor = connection.cursor()
    cursor.execute(f"SELECT TOP 1 * FROM {table_name}")
    row = cursor.fetchone()
    if row:
        column_name = next(column[0] for column in cursor.description)
        return row[column_name]
    else:
        return None                
              
Tags: