SQLAlchemy-Based Database Table Column Fetcher

  • Share this:

Code introduction


This function uses the SQLAlchemy library to connect to the database, reflect the table structure, and query the column names of the specified table.


Technology Stack : SQLAlchemy, Python

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql import select

def fetch_table_columns(engine_name, table_name):
    """
    This function fetches all columns from a specified table in a database using SQLAlchemy.
    """
    # Create an engine that connects to the database
    engine = create_engine(engine_name)
    
    # Connect to the engine
    connection = engine.connect()
    
    # Reflect the tables from the database
    metadata = MetaData()
    table = Table(table_name, metadata, autoload_with=engine)
    
    # Select all columns from the table
    select_statement = select([table])
    
    # Execute the query and fetch all columns
    result = connection.execute(select_statement).fetchall()
    
    # Close the connection
    connection.close()
    
    # Return the list of column names
    return [row[0].name for row in result]

# Example usage
# Assuming you have a database named 'example_db' and a table named 'users'
# columns = fetch_table_columns('sqlite:///example_db.db', 'users')
# print(columns)