Python SQLAlchemy – Get column names dynamically
In this article, we are going to see how to dynamically get the column names of a table in SQLAlchemy using Python.
Used database for demonstration:
So, our student table has 5 columns namely sno, name, dob, class, and section, and our task is to fetch all these column names in our Python code.
First of all, we will import the sqlalchemy module, create an engine and then create a connection with the database. Then we will execute a query on the table whose column names we want.
Now using the keys method of that result object obtained by running the query we can get all the column names dynamically.
We can also use the result.cursor.description of the result object. The result.cursor.description is a list containing tuples whose 1st element is the name of the column. Let us run a for loop on it and store the first element of it in our custom columns variable.
Please Login to comment...