Search code examples
pythonmysqlmysql-pythonpymysql

How to get a map of all data types from pymysql.cursor.description?


For sql_select_query = 'select * from table', you can use pymysql python module to connect to MySql database and cursor.description to extract values.

def conn():
    myDb=pymysql.connect(server,user,password,database)
    return myDb

dbc = conn() #database connection
dbCursor = dbc.cursor() # cursor

# gathers all column field names and their type
field_names_and_type = [desc[:2] for desc in dbCursor.description]

Example output:

print(field_names_and_type)

[('ItemId', 1), ('ItemName', 3)]

type 1 is nvchar

type 3 is int

Question: how to i map these? I've checked pymysql docs but could not find the mapping for cursor.description output.


Solution

  • Pymysql type codes are defined in pymysql.constants.FIELD_TYPE

    DECIMAL = 0
    TINY = 1
    SHORT = 2
    LONG = 3
    FLOAT = 4
    DOUBLE = 5
    NULL = 6
    TIMESTAMP = 7
    LONGLONG = 8
    INT24 = 9
    DATE = 10
    TIME = 11
    DATETIME = 12
    YEAR = 13
    NEWDATE = 14
    VARCHAR = 15
    BIT = 16
    JSON = 245
    NEWDECIMAL = 246
    ENUM = 247
    SET = 248
    TINY_BLOB = 249
    MEDIUM_BLOB = 250
    LONG_BLOB = 251
    BLOB = 252
    VAR_STRING = 253
    STRING = 254
    GEOMETRY = 255
    
    CHAR = TINY
    INTERVAL = ENUM