-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstudentcourse.py
92 lines (66 loc) · 2.2 KB
/
studentcourse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# ------------
# Instructions
# ------------
# To run this script, first install the necessary libraries via pip:
# pip install mysql-connector colorama pandas
# Alternatively, in conda/mamba, see: mysql-connector-python
# Next, run this script via python:
# python studentcourse.py
# Note that you may need to change the server settings based on your configuration (see mysql.connector.connect below).
# ----------------
# Import Libraries
# ----------------
import mysql.connector
import colorama
from colorama import init, Fore, Back, Style
import pandas as pd
init() # for colorama
# -----------------------------
# Define Custom Print Functions
# -----------------------------
def PrintHeading (headingText):
print(
Fore.RED + Back.BLUE + Style.BRIGHT +
"\n" + headingText + "\n" +
Style.RESET_ALL
)
def PrintQueryResult (result):
resultDF = pd.DataFrame(result)
fieldNames = [i[0] for i in cursor.description]
resultDF.columns = fieldNames
print(resultDF)
# -------------
# Connect to DB
# -------------
db = mysql.connector.connect(
database = "studentcourse",
host = "localhost",
user = "root",
passwd = "root"
)
cursor = db.cursor()
# --------------------
# DBI Command Examples
# --------------------
PrintHeading("List all tables:")
cursor.execute("SHOW TABLES;");
PrintQueryResult(cursor.fetchall())
PrintHeading("Describe (a MySQL keyword) student table:")
cursor.execute("DESCRIBE student;");
PrintQueryResult(cursor.fetchall())
# ---------------
# Running Queries
# ---------------
PrintHeading("Return an Entire Table:")
cursor.execute("SELECT * FROM student;");
PrintQueryResult(cursor.fetchall())
PrintHeading("Group By and Having:")
cursor.execute("SELECT studentid, COUNT(courseid) FROM takes WHERE courseid != 3100 GROUP BY studentid HAVING COUNT(courseid) > 2;");
PrintQueryResult(cursor.fetchall())
PrintHeading("Joining Multiple Tables at Once:")
cursor.execute("SELECT * FROM student NATURAL JOIN major NATURAL JOIN takes NATURAL JOIN course;");
PrintQueryResult(cursor.fetchall())
# ------------------
# Disconnect from DB
# ------------------
db.close()