Database Interaction Functions with pyodbc

  • Share this:

Code introduction


This code block defines three functions: connecting to a database, fetching a random row from a specified table in the database, and closing the database connection. These functions interact with an SQL Server database using the pyodbc library.


Technology Stack : pyodbc, SQL Server

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import pyodbc
import random

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

def fetch_random_row(conn):
    # This function fetches a random row from a specified table in the database
    cursor = conn.cursor()
    cursor.execute("SELECT TOP 1 * FROM [YourTableName] ORDER BY NEWID();")
    row = cursor.fetchone()
    cursor.close()
    return row

def close_connection(conn):
    # This function closes the connection to the database
    conn.close()

# Example usage
conn = connect_to_database('your_server', 'your_database', 'your_username', 'your_password')
random_row = fetch_random_row(conn)
print(random_row)
close_connection(conn)                
              
Tags: