Created
January 1, 2021 17:25
-
-
Save Kalbra/92952724053198c23c8ee3efc26f6d4d to your computer and use it in GitHub Desktop.
Class to easierly manage mysql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
# Sets env variables | |
HOST = "localhost" | |
USER = "user" | |
PASSWORD = "password" | |
# This class is for easier sql querying | |
class Database: | |
conn = None | |
# The class required the name of the database | |
def __init__(self, database): | |
self.database = database | |
self.connect() | |
# This part connects the database by using the pre defined values | |
def connect(self): | |
self.conn = mysql.connector.connect( | |
host=HOST, | |
user=USER, | |
password=PASSWORD, | |
database=self.database, | |
auth_plugin='mysql_native_password' | |
) | |
# This part is the actual getting and inserting part | |
def query(self, command): | |
# Try to connect to the database this is required, cause after a while the | |
# following error will happen | |
try: | |
cursor = self.conn.cursor(buffered=True) | |
cursor.execute(command) | |
self.conn.commit() | |
# If the error occurred it will automatically reconnect | |
except (AttributeError, mysql.connector.OperationalError): | |
self.connect() | |
cursor = self.conn.cursor() | |
return cursor | |
# This is the command for getting data out of the database | |
def get(self, command): | |
cursor = self.query(self.SQLInjectionProtector(command)) | |
result = cursor.fetchall() | |
return result | |
# This is the command for inserting the data into the database | |
def insert(self, command): | |
self.query(self.SQLInjectionProtector(command)) | |
self.conn.commit() | |
# This is the SQL protection static method for SQL protection | |
@staticmethod | |
def SQLInjectionProtector(data): | |
data.replace(";", "") | |
data.replace('"', "") | |
data.replace("--", "") | |
data.replace("/*", "") | |
data.replace("*/", "") | |
data.replace("xp_", "") | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment