Python cannot connect to MySQL if declare in a class -
i'm newbie in python. i'm trying use python connect mysql server. wrote guides mysql official page, ok. but, when create connector class, raised error "mysql connection not available"
here class
import mysql.connector 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 err: if err.errno == errorcode.er_access_denied_error: print("something wrong user name or password") elif err.errno == errorcode.er_bad_db_error: print("database 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 none") return self.cursor = self.connection.cursor() if(self.cursor!=none) : self.cursor.execute(query) else: print("cursor 'none'") ## end execute ## end mysql connector class ## begin run objconnect = mysqlconnector() objconnect.open() objconnect.execute("select * user")
please show me way solution , explained me why code has error.
thanks!
edited
finally, mata , alecxe me solve problem, don't know solution choosen. summary here has mistake me: 1. remove statement. 2. using **
in self.connection = mysql.connector.connect(**self.configs)
even if correct error alecxe pointed out, code still won't work.
the finally
block ensures each connection closed before returned, no matter wheather there exception or not, open
method returns closed connections.
Comments
Post a Comment