First off, I’ll need a method that will establish a connection to a running MySql database:
print 'Attempting to get connection to database.'
conn = None
conn = connector.connect(user=configs.db_username,
print 'Connection to MySQL instance returned.'
except mysql.connector.Error as e:
message = e.message
Next, I’ll want to clean up any connections and resources once I am done with them:
print 'Attempting to release connections.'
print 'Cursor closed.'
print 'Transaction committed.'
except Exception as e:
print 'Rolling back transaction.'
message = e.message
print 'Connection closed.'
Next, I’ll want a master method that will issue SQL commands / queries and return the appropriate results:
def executeSql(self, sql,mode = 'command'):
print 'Mode: ' + mode + '. Executing query:'
out = -1 if mode is not 'query' else 
conn = self.getMysqlConnection()
if conn is not None:
cursor = conn.cursor()
if mode is 'insert':
out = cursor.lastrowid
elif mode is 'query':
out = 
for row in cursor:
size = len(row)
sub = 
for i in range(0,size):
elif mode is 'command':
out = cursor.rowcount
As a side note, I personally found the documentation for the MySql connector on the MySql website to be severely lacking. It didn’t run through specific cases such as Get, List and Delete in that much detail, and I found myself writing code just to print out the results just so that I could see what was being returned by the DB. I’m hoping that some of what I’ve written here will help others out.
Okay, back to the connector:
Lastly, in order to fulfill the contact, here are the rest of the methods:
def executeInsert(self, insertSql):
return self.executeSql(insertSql, 'insert')
def executeQuery(self, querySql):
return self.executeSql(querySql, 'query')
def executeCommand(self, commandSql):
Now, in order to get access to this implementation in a way that is based on user-defined configuration values, all I need to do is this:
print 'Getting connection for DB: ' + configs.db_vendor
connection = None
if configs.db_vendor is 'mysql':
connection = MySqlConnector()
print 'Type of connection being returned: ' + connection.__class__.__name__
My next post will tie this all together, and after that – testing!