from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

import mysql.connector

def Index(request):
    return render(request, "DB/index.html")

def connectToMyDB():
    return mysql.connector.connect(
        host="localhost",
        user="Student",
        passwd="P@$$w0rd",
        database="myDB"
    )

def Ex01(request):
    try:
      server = mysql.connector.connect(
        host="localhost",
        user="Student",
        passwd="P@$$w0rd",
      )
      return HttpResponse("Server is running")
    except Exception as e:
      return HttpResponse(f"Server is not Running:{e}")

def Ex02(request):
    try:
        db = connectToMyDB()
        return HttpResponse("MyDB is ready")
    except Exception as e:
        return HttpResponse(f"MyDB is not ready:{e}")

def Ex03(request):
    try:
        db = connectToMyDB()
        cursor = db.cursor()
        cursor.execute("SELECT name FROM Country")
        countries = cursor.fetchall()
        html = "<Select>"
        for country in countries:
            html += f"<option>{country[0]}</option>"
        html += "</Select>"
        return HttpResponse(html)
    except:
        return HttpResponse("")
