sqlalchemy print column names code example

Example 1: how to print out column name differently in mysql

-- MySQL

SELECT column1 AS name1, column2 AS name2
FROM table1;

-- AS allows your to replace the name of a column when outputting but does not
-- actually change the column name within the database.

Example 2: how to get column name in db from an sqlalchemy attribute model

class User(Base):
    __tablename__ = 'user'
    id = Column('id', String(40), primary_key=True)
    email = Column('email', String(50))
    firstName = Column('first_name', String(25))
    lastName = Column('last_name', String(25))
    addressOne = Column('address_one', String(255))


from sqlalchemy.inspection import inspect
# columns = [column.name for column in inspect(model).c]

# Also if we want to know that User.firstName is first_name then:
columnNameInDb = inspect(User).c.firstName.name
# The following will print: first_name
print(columnNameInDb)

Tags:

Sql Example