Tuesday, 25 August 2020

How to fetch the datatype with column and create a dictionary

Mysql table have student have 2 tables students and teach

Code is below

def tbl_col_names(table):
    db = {}
    for i in table:
        cursor.execute("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= '%s'" % (i))
        tabledescription = cursor.fetchall()
        print ('tableDesc1', tabledescription)
        tableDescription1 = [i[0] for i in tabledescription]
        print (tableDescription1)
        db[i] = tableDescription1
        with open('data.json','w') as f:
            db1 = json.dumps(db)
            test = (f"data ='[{db1}]'")
            f.write(test)
    return db
cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema='databasename'")
ecords = cursor.fetchall()
print (records)
member = [i[0] for i in records]
print ('member',member)
allcolumnvalues = tbl_col_names(member)
print ('all',allcolumnvalues )

data.json output is below

data = '[{"students": ["student_no"], "teach": ["last_name", "course_no"]}]'

How to fetch the data type along with column name

Below is the mysql query to get column name along with data type

select COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where table_name='student';
cursor.execute("select COLUMN_NAME,DATA_TYPE  from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= '%s'" % (i))

My expected out data.json is below

data = '[{"students": {"student_no":"int"}, "teach": {"last_name":"varchar", "course_no":"int"}}]'


from How to fetch the datatype with column and create a dictionary

No comments:

Post a Comment