I'm newbie in Python. I'm trying to use Python to connect MySQL Server. I wrote like guides from MySQL official page, it was OK. But, when I create a connector class, it raised the error "MySQL Connection not available"
Here is my class
import mysql.connector
from mysql.connector import errorcode
## BEGIN MySQL Connector Class
class MySQLConnector :
configs = {
"user":"root",
"password":"",
"host":"127.0.0.1",
"database":"python_db",
"raise_on_warnings": True
}
cursor = None
connection = None
## BEGIN Constructor
def __init__(self, configs = {}) :
if(any(configs)!=False) :
self.configs = configs
## END Constructor
## BEGIN Open
def open(self) :
try:
self.connection = mysql.connector.connect(self.configs)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
finally:
self.connection.close()
return self.connection
## END Open
## BEGIN close connection
def close(self) :
self.cursor.close()
self.connection.close()
## END close connection
## BEGIN execute
def execute(self, query) :
if(self.connection == None) :
print("Connection is None")
return
self.cursor = self.connection.cursor()
if(self.cursor!=None) :
self.cursor.execute(query)
else:
print("Cursor is 'None'")
## END execute
## END MySQL Connector Class
## BEGIN RUN
objConnect = MySQLConnector()
objConnect.open()
objConnect.execute("SELECT * FROM User")
Please show me the way to solution and explained me why my code has error.
Thanks!
EDITED
Finally, mata and alecxe help me to solve this problem, I don't know which solution to be choosen. I summary here for someone has mistake like me:
1. Remove the finally statement.
2. Using ** in self.connection = mysql.connector.connect(**self.configs)
## BEGIN MySQL Connector Class...## END MySQL Connector Class- this makes any python programmer's eyes bleed.if(any(configs)!=False)seems wrong to me, as the condition nearly always is true. What did you mean to accomplish?if configs:(testing ifconfigs is non-empty)? Orif any(configs):(testing if it has at least one non-empty key)? What you do is testing if it has a value which evaluates to a tru-ish key (!) and compare that withFalse, which could never be the way except if it only has falsey values or is empty. So it is the same asif any(configs):, but very more complicated and very harder to understand.