Python CRUD

Let’s do the same thing with MySql

pip install MySQL-python
import MySQLdb

class mydbconn():
    def __init__(self):
        self.con = MySQLdb.connect('x', 'x', 'x', 'x')

    def get_columns(self,table):
        cuc = self.con.cursor()
        cursData = cuc.execute("SHOW columns FROM " + table)
        HEADERS = cuc.fetchall()
        keyName = HEADERS[0][0]
        keyLen = self.lenFunction(HEADERS[0][1])
        return keyName, keyLen, HEADERS

    def lenFunction(self,varCharString):
        x = varCharString.find("(")
        varCharString = varCharString[x+1:]
        x = varCharString.find(")")
        varCharString = varCharString[:x]
        return int(varCharString)

if __name__=="__main__":
    con = mydbconn()
    keyName, keyLen, h = con.get_columns("customer")
    for i in h:
        print i

On the fifth line of the program, use your MySql credentials. Sometimes the first parameter is localhost, the second x is the username for the database, the password is third and the name of the database is fourth.

You also have to change the parameter in line 2 of the main section to the name of the table you are using. This routine also has been used with databases that had a key other than named id for the first field, and it was important to have the name of the key and its length to proceed with scaffolding

In the Sqlite3 sqlalchemy example, we got a list of field names. In this example, we get a tuple of tuples. At this point, tuples might be a preferred format, they are immutable and hashable, and a utility crud function would not need to add and remove things from the tuple. However, in a more sophisticated scaffolding environment, you would add things like a field for password verification or especially remove things, like the ability to change certain fields.