SQL Server Database Interaction Functions

  • Share this:

Code introduction


This code defines four functions for connecting to a database, retrieving table columns, inserting a new row, and closing the connection. These functions use the pyodbc library to interact with a SQL Server database.


Technology Stack : pyodbc, SQL Server, database connection, table operations

Code Type : The type of code

Code Difficulty :


                
                    
import pyodbc

def connect_to_database(server, database, username, password):
    # Establish a connection to the 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 get_table_columns(connection, table_name):
    # Retrieve the columns of a specified table from the database
    cursor = connection.cursor()
    cursor.execute(f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{table_name}'")
    columns = cursor.fetchall()
    return [column[0] for column in columns]

def insert_row(connection, table_name, data):
    # Insert a new row into a specified table with the given data
    columns = get_table_columns(connection, table_name)
    placeholders = ', '.join(['?'] * len(columns))
    sql = f'INSERT INTO {table_name} ({", ".join(columns)}) VALUES ({placeholders})'
    cursor = connection.cursor()
    cursor.execute(sql, data)
    connection.commit()

def close_connection(connection):
    # Close the database connection
    connection.close()