#!/usr/bin/python
#=====================================================================================
# Get Metadata 
#===================================================================================== 
import pymysql as mydb                  #Mysql 3x database driver
import HTTPparam
 
print("Content-Type: text/html \n")     #required http response header (w/ extra line)

print('''
    <html>
    <head>
    <title>Get Metadata from DB Query</title>
    </head>
    <body>
    <h1>Get Database Metadata</h1>
    <h2>For 'payment' Table</h2>
    <h3><i>(col_name, col_type, col_size, etc.) </i></h3>
''')
 
host   = 'localhost'               #the local host
port   =  3306                     #MySql port number
userid = 'demo'                    #the userid
pswd   = 'demo'                    #the password    
db     = 'demo'                    #the name of the mysql database
 
try:
    conn = mydb.connect(host=host,user=userid,password=pswd,database=db)     #connect to host
     
    cursor = conn.cursor()               #create a cursor
 
    sql = 'select * from payment'        #build your query
 
    cursor.execute(sql);                 #execute the query
 
except mydb.Error as e:
    print("Could not establish connection", '<br>') 
    print(e.errno, e.msg, '<br>')
    exit()
 
print("<table border=1>")
print("<tr bgcolor=tan><th>Column Name<th>Type<th>Display Size<th>Internal Size<th>Precision<th>Scale<th>Nullable?")

numOfCol = len(cursor.description)             #number of column retrieved by the query 

for colInfo in cursor.description :
    col_name          = colInfo[0]             #the column name
    col_type          = colInfo[1]             #the column type
    col_display_size  = colInfo[2]             #display size
    col_internal_size = colInfo[3]             #internal size
    col_precision     = colInfo[4]             #precision
    col_scale         = colInfo[5]             #scale (number of decimal places)
    col_nullable      = colInfo[6]             #is it nullable

    print("<tr>")
    print("<td>", col_name)
    print("<td>", col_type)
    print("<td>", col_display_size)
    print("<td>", col_internal_size)
    print("<td>", col_precision)
    print("<td>", col_scale)
    print("<td>", col_nullable)

print("</table>")

cursor.close()                            #close the cursor/buffer
conn.close()                              #close the connection



#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/staff/sultan/public_html/cgi-bin/python')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#=================================================================================