class DB: def __init__(self, app, mysql): self.app = app self.mysql = mysql self.user = app.config["DB_USERNAME"] self.password = app.config["DB_PASSWORD"] self.database = app.config["DB_DATABASE_NAME"] self.host = app.config["DB_HOST"] def connectDB(self): # Provide the database connection details self.app.config['MYSQL_DATABASE_USER'] = self.user self.app.config['MYSQL_DATABASE_PASSWORD'] = self.password self.app.config['MYSQL_DATABASE_DB'] = self.database self.app.config['MYSQL_DATABASE_HOST'] = self.host # Connect to the database try: self.conn = self.mysql.connect() cursor = self.conn.cursor() # Return the cursor object return cursor except: return False def selectionQuery(self, sql, args = False): # Takes the SQL and any arguments. Arguments must be in the form of a tuple # Returns a bool value for the success of the query and the data or the error statement cursor = self.connectDB() if args is False: try: cursor.execute(sql) data = cursor.fetchall() return True, data except (self.conn.Error, self.conn.Warning) as e: print(e) return False, "Error in query: " + e else: try: cursor.execute(sql, args) data = cursor.fetchall() return True, data except (self.conn.Error, self.conn.Warning) as e: print(e) return False, "Error in query: " + e def changeQuery(self, sql, args = False): # Takes the SQL and any arguments. Arguments must be in the form of a tuple # Returns a bool value for the success of the query and the error statement is required cursor = self.connectDB() if args is False: try: cursor.execute(sql) self.commitChanges() return True, True except (self.conn.Error, self.conn.Warning) as e: print(e) return False, "Error in query: " + str(e) else: try: cursor.execute(sql, args) self.commitChanges() return True, True except (self.conn.Error, self.conn.Warning) as e: print(e) return False, "Error in query: " + str(e) def commitChanges(self): self.conn.commit() def getConn(self): return self.conn def close(self): self.conn.close()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question