How to use table metadata In SQL
This returns the ‘key’ for the Table Metadata.
Syntax: sqlalchemy.schema.Table.key
Python
import sqlalchemy as db from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT) engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks" ) # CREATE THE TABLE MODEL TO USE IT FOR QUERYING class Profile(Base): __tablename__ = 'profile' email = db.Column(db.String( 50 ), primary_key = True ) name = db.Column(db.String( 100 )) contact = db.Column(db.Integer) # PREPARING SQLALCHEMY QUERY with engine.connect() as conn: result = conn.execute( db.select([Profile.email, Profile.name, Profile.contact])) # VIEW THE COLUMN NAMES print (result._metadata.keys) |
Output:
How to get column names from SQLAlchemy?
In this article, we will discuss how to get column names using SQLAlchemy in Python.
SQLAlchemy is an open-source SQL toolkit and object-relational mapper for the Python programming language released under the MIT License. It gives full power and flexibility of SQL to an application. To follow along with this article, we need to have sqlalchemy and anyone database installed in our system. We have used the MySQL database for this article’s understanding.
To install sqlalchemy using pip:
pip install sqlalchemy
For our examples, we have already created a Profile table under Geeks4Geeks schema name, which we will be using:
There are different ways through which we can get the column names in SQLAlchemy.
Contact Us