Lab 02 Exercises
Lab 02 Exercises
1. In Lab01 question 2, we used the PhpMyAdmin tool as an interface for accessing the
MySQL DBMS back end. In this question, we use a programming interface to directly access
the created databases of the MySQL DBMS.
MySQL Connector for Python (https://dev.mysql.com/doc/connector-python/en/) provides a
database connectivity mechanism for communicating with MySQL servers through a Python
program. Please read the above page link and install the ‘mysql.connector’ on your
Python3 runtime environment. The following is a simplified code segment that enables the
login to your MySQL account and displays the names of all databases.
import mysql.connector
from getpass import getpass
from mysql.connector import connect, Error
def main():
try:
with connect(
host="fosmysqlprd01.its.auckland.ac.nz",
user=input("Enter username: "),
password=getpass("Enter password: "),
) as connection:
print('DATABASE NAMES')
dbexec(connection, "SHOW DATABASES")
except Error as e:
print(e)
main()
Your task is extending the above program in order to achieve the additional functions below:
• Allow the user to select a database and display its tables. The DML statements are
‘USE database_name' and 'SHOW TABLES'. Note that database_name should
be replaced with an actual database name.
• Allow the user to select a table and display its content. The DML statement is
'SELECT * FROM table_name'. Note that table_name should be replaced with
an actual table name.
• Allow the user to enter a DML query statement and display the result of the query.
Notes on connectivity to the database: Because the MySQL database server is installed
within the UOA intranet, a secured connection is required to establish connectivity to the
database. Here are three possible options:
(b) For MacOS and Linux users, please run the following command in a terminal:
Remember to replace 'your_upi' in the command above with your own UPI. After the SSH
tunneling has been established, you can run the code on your local machine through the
SSH tunnel (you need to change the host address in the code to '127.0.0.1').
Note that you do not need to copy the code onto the server login account. You just need to
keep the server login window active in the background and run the code from your local
machine.
A sample output of the completed program is shown as follows. Note that ‘abcd001’ is used
as the example login UPI. You should replace it with your own student UPI value.
2. Consider the following ER diagram for part of a BANK database and answer the
questions below. Note that each bank can have multiple branches, and each branch can
have multiple accounts and loans.