bozo-backend/Database.py
2023-06-04 12:16:15 +02:00

57 lines
1.7 KiB
Python

import mysql.connector
import User
class Database:
def __init__(self, host, port, user, password):
"""
: param host: The ip of the database
: type host: str
: param port: The port of the database
: type port: int
: param user: The user to login on the database
: type user: str
: param password: The password of the user
: type password: str
"""
self.mydb = mysql.connector.connect(
host = host,
port = port,
user = user,
password = password,
)
self.cursor = self.mydb.cursor()
self.cursor.execute("SHOW DATABASES");
if (not "zeolak" in self.cursor):
self.cursor.execute("CREATE DATABASE zeolak")
self.mydb = mysql.connector.connect(
host = host,
port = port,
user = user,
password = password,
database = "zeolak"
)
self.cursor = self.mydb.cursor()
def _create_table(self, name: str, content: dict):
command: str = f"CREATE TABLE {name} ("
for item in content.keys():
command += f"{item[0]} {item[1]}, "
command += ")"
self.cursor.execute(command)
def create_user_table(self):
self.cursor.execute("SHOW TABLES");
if (not "users" in self.cursor):
data = {
"email": "VARCHAR(255)",
"username": "VARCHAR(255)",
"first_name": "VARCHAR(255)",
"last_name": "VARCHAR(255)",
"password": "VARCHAR(255)"
}
self._create_table("users", data)
def add_user(self, user: User):
self.cursor(user.to_insert_sql())