Note that there are some explanatory texts on larger screens.

plurals
  1. POPython cannot connect to MySQL if declare in a class
    primarykey
    data
    text
    <p>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"</p> <p>Here is my class</p> <pre><code>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") </code></pre> <p>Please show me the way to solution and explained me why my code has error.</p> <p>Thanks!</p> <hr> <p><strong>EDITED</strong></p> <p>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 <code>**</code> in <code>self.connection = mysql.connector.connect(**self.configs)</code></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload