I have a simple SQL command via pymsql to retrieve data
db = pymysql.connect(
db=DATABASE,
passwd=DB_PASSWORD,
host=DB_HOST,
user=DB_USER,
)
cursor = db.cursor()
cursor.execute("""
select flight, aircraft_model
from flights
where flights.aircraft_type in ('boeing', 'airbus')
""")
res = cursor.fetchall()
This will return a array of tuples e.g.
[
('tk123', 'b737'),
('us123', 'a230')
]
How can I have the first tuple to be the column names e.g.
[
('flight', 'aircraft_model')
('tk123', 'b737'),
('us123', 'a230')
]
I thought it was quite obvious from above, but I am not looking for similar to MySQL: Get column name or alias from query as that has a different output format than I specified.
[('column', 'names'), *cursor.fetchall()]?DictCursorclass in your connect statement, eg.pymysql.connect(cursorclass=pymysql.cursors.DictCursor, ...). This will return the query results as a collection of dictionaries rather than tuples.select flight, aircraft_modelthen you could extract names using string functions, and later put as first element on list[(...tuple with names ...), *cursor.fetchall()]. Or probably you could get columns fromcursor.description. And you have 50 places then you should create one function which gets only SQL query and it executes query, and it also adds first row with columns, and use this function in 50 places.