Monday, September 7, 2015

Python Mysql Connector Manual Configuration And Connection

Mysql Connector class assignment based on documentation always establish connection on class initialization or constructor, even if it looks like a configuration init.
On documentation here stated that
The MySQLConnection constructor initializes the attributes and when at least one argument is passed, it tries to connect to the MySQL server.
Sometimes we don't want auto-connect on class constructor stage, and make another function to establish connection with Exception handling.

To achive that, we can write like below:
import mysql.connector

Class DB():

  def __init__(self, username, server_name, database_name):
    self.dbConfig = {"user" : username, "host" : server,
        "database" : name_database}
    self.cnx = mysql.connector.MySQLConnection()

  def connectDB(self):
    if not self.con.is_connected():
      print "connected .. "
    except Exception as ex:
      print "Error: " + str(ex)
With above code, we can separate between constructor and connect method and catch exception for further action.

If you had better idea, please share on comment. Thank you.