Friday 20 November 2020

SQLAlchemy accessing column types from query results

I am connecting to a SQL Server database using SQLAlchemy (with the pymssql driver).

import sqlalchemy

conn_string = f'mssql+pymssql://{uid}:{pwd}@{instance}/?database={db};charset=utf8'
sql = 'SELECT * FROM FAKETABLE;'

engine = sqlalchemy.create_engine(conn_string)
connection = engine.connect()
result = connection.execute(sql)
result.cursor.description

which results in:

(('col_1', 1, None, None, None, None, None),
 ('col_2', 1, None, None, None, None, None),
 ('col_3', 4, None, None, None, None, None),
 ('col_4', 3, None, None, None, None, None),
 ('col_5', 3, None, None, None, None, None))

As per PEP 249 (cursor's .description attribute):

The first two items (name and type_code) are mandatory, the other five are optional and are set to None if no meaningful values can be provided.

I am assuming the integers (1, 1, 4, 3, 3) are column types.

My two questions:

  1. How to map these integers to data types (like char, integer, etc.)?
  2. Are these SQL data types? If no, is it possible to get the SQL data types?

FWIW, I get the same result when using raw_connection() instead of connect().

Came across three questions along similar lines (which do not answer this specific question). I need to use the connect() + execute() approach.



from SQLAlchemy accessing column types from query results

No comments:

Post a Comment