Skip to content

Instantly share code, notes, and snippets.

@Kalbra
Created January 1, 2021 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kalbra/92952724053198c23c8ee3efc26f6d4d to your computer and use it in GitHub Desktop.
Save Kalbra/92952724053198c23c8ee3efc26f6d4d to your computer and use it in GitHub Desktop.
Class to easierly manage mysql
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