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.connectorWith above code, we can separate between constructor and connect method and catch exception for further action.
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():
try:
self.cnx.connect(**self.dbConfig)
print "connected .. "
except Exception as ex:
print "Error: " + str(ex)
If you had better idea, please share on comment. Thank you.
No comments:
Post a Comment