0% found this document useful (0 votes)
18 views

eBOOKPython5 3 2023

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

eBOOKPython5 3 2023

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

>>>

FATIMAH RAHMAT | MOHAMAD IQBAL HAKIM CHE OMAR | NURUL SHAKIRAH MOHD ZAWAWI
FATIMAH RAHMAT
MOHAMAD IQBAL HAKIM CHE OMAR
NURUL SHAKIRAH MOHD ZAWAWI

First Edition 2023


Copyright ©2023
All rights reserved. No part of this publication may be reproduced,
distributed, or transmitted in any form or by any means, including
photocopying, recording, or other electronic or mechanical methods,
without the prior written permission of the publisher, except in the case
of brief quotations embodied in critical reviews and certain other noncommercial
uses permitted by copyright law. For permission requests, write
to the publisher, addressed “Attention: Permission Coordinator,” at the
address below.

Politeknik Mersing
Jalan Nitar,
86800 Mersing
Johor Darul Ta’zim
Telephone : 07-7980001
Fax : 07-7980002
Website : https://pmj.mypolycc.edu.my/

Printed in Malaysia
First Printing, 2023
eISBN : 978-967-2904-57-1

Authors :
Fatimah Rahmat
Mohamad Iqbal Hakim Che Omar
Nurul Shakirah Mohd Zawawi
Python and MySQL for Beginner

The need to share knowledge and experience on how the Python programming
language could have a positive impact on the learning process led to the
creation of this book focuses on the installation process, use of MySQL for
database connections, and fundamental Python language concepts.

This book offers helpful resources, advice, and examples, especially for
students and anybody else interested in learning the Python programming
language.

The Create, Read, Update, and Delete (CRUD) component of an application


employing Python scripts using MySQL is also demonstrated in this book's
sample examples.

This book is intended to assist readers in achieving their goals.


Python and MySQL for Beginner

I. INTRODUCTION
What is Python Programming? ................................... 2
Basic Principles of Python ............................................... 3

II. REQUIREMENTS
TABLE OF CONTENTS

What is needed? .................................................................. 5


Visual Studio Code versus PyCharm versus
IDLE ............................................................................................. 6
Minimum requirements for:
Visual Studio Code (VS Code) installation 8
PyCharm installation ..................................................... 8
IDLE installation ................................................................. 9
Laragon ...................................................................................... 10

III. INSTALLING
Installing Python and IDE Environment Setup .. 12

IV. FIRST PROJECT ACTIVITY


Set up local web server Laragon ................................. 17
Choose your favourite IDE either PyCharm or
VSCode ........................................................................................ 19
Activity
Create insertData.py ...................................................... 25
Create deleteData.py ..................................................... 26
Create displayData.py ................................................... 27
Create updateData.py ................................................... 28
Import module in main.py ........................................... 29
Create database function in main.py ................... 29
Drop database function in main.py ...................... 30
Create table function in main.py ............................ 30
Drop table function in main.py ................................ 31
Display all databases function ................................. 31
Finish the whole program ........................................... 32

References ................................................................................ 33

"PYTHON IS AN EASY-TO-USE LANGUAGE FOR BEGINNERS, YET IT IS


POWERFUL ENOUGH FOR EXPERTS." -KENNETH REITZ-
CHAPTER 1
INTRODUCTION

1
Python and MySQL for Beginner

What is Python Programming?

Interpreted
Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL
and PHP. Execution is implemented directly and freely from source
without need to be compiled into machine code or binary format.

Interactive
You can actually sit at a Python prompt and
interact with the interpreter directly to write your
programs.

Object-Oriented
Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.

Beginner’s Language
Python is a great language for the beginner- level
programmers and supports the development of a
wide range of applications from simple text
processing to WWW browsers to games.

Dynamically typed language


It doesn’t know about the type of the variable until the code is run.
So declaration is of no use. What it does is, It stores that value at
some memory location and then binds that variable name to that
memory container.

Python is a high-level programming language that was first released in 1991 by Guido van Rossum.
The language was designed to be easy to read and write, with a focus on code readability. Python's
design philosophy emphasizes code readability, and its syntax allows programmers to express
concepts in fewer lines of code than languages like C++ or Java.

2
Python and MySQL for Beginner

Basic Principles of Python

Basic Core language


Python is designed so that there really isn’t that much to learn in the basic language. For example, there
is only one basic structure for conditional programming (if/else/elif), two looping commands (while and
for), and a consistent method of handling errors (try/except) which apply to all python programs.

Modules
Self-contained programs which define a variety of functions and data types that you can call in order to
do tasks beyond the scope of the basic core language by using the import command.

Object oriented programming


A basic concept of object oriented programming is encapsulation, the ability to define an object that
contains your data and all the information a program needs to operate on that data. In this way, when
you call a function (known as a method in object-oriented lingo), you don’t need to specify a lot of
details about your data, because your data object ``knows’’ all about itself. In addition, objects can
inherit from other objects, so if you or someone else has designed an object that’s very close to one
you’re interested in, you only have to construct those methods which differ from the existing object,
allowing you to save a lot of work.

Namespace and variable scoping


The same variable name can be used in different parts of a program without fear of destroying the
value of a variable you’re not concerned with.

Exception handling
When you’re performing an operation that might result in an error, you can surround it with a try loop,
and provide an exception clause to tell python what to do when a particular error arises.

Some of the most popular Python libraries and frameworks include:


NumPy, a library for numerical computing
pandas, a library for data manipulation and analysis
scikit-learn, a machine learning library
TensorFlow, a library for deep learning
Django, a web framework
Flask, a micro web framework

3
CHAPTER 2
REQUIREMENTS

4
Python and MySQL for Beginner

What is needed?
Choose ONE of every category

IDE
(Integrated Development Environment)

Visual Studio Code


(VS Code)

PyCharm
Web Server

IDLE
Laragon

XAMPP

5
Python and MySQL for Beginner

Table 1: Visual Studio Code versus PyCharm versus IDLE

CRITERIA VS Code PyCharm IDLE

Code editor that


An IDE (Integrated An IDLE Integrated
provides a similar
Environment Development Development and
experience to an IDE
Environment). Learning Environment
through extensions.

Lightweight because it Consumes a lot of Coded in 100% pure


Performances does not need much resources because it Python, using the tkinter
space. requires a lot of memory GUI toolkit
and large storage
space.

Free and compatible Cross-platform: works


Cross platform IDE.
with all platforms: mostly the same on
Platform More powerful and has
Windows, Linux and Windows, Unix, and
a commercial version.
Mac macOS

Potential errors are Main features is the Python shell window


Features automatically “Search Anywhere” that (interactive interpreter)
highlighted in red, allows you to search with colorizing of code
making it easy to find outside your project. input, output, and error
and fix errors. It goes a Can find files, classes, messages.
step further by adding symbols, and user
the Issues tab, listing all interface elements Multi-window text
potential bugs in one even if they don’t exist editor with multiple
place and making it in your current project. undo, colorizing, smart
easy to review. To use indent, call tips, auto
Python with VS Code, Code completion is completion, and other
you need to install the better with PyCharm. It features.
Python formatter and displays function
linter. signatures as part of the Search within any
autocomplete selection window, replace within
list. editor windows, and
search through multiple
Has some additional files (grep).
features such as Sort by Debugger with
Name, Quick persistent breakpoints,
Documentation and stepping, and viewing of
Quick Definition. Quick global and local
documentation shows namespaces
the function’s signature
and return type, as well Configuration,
as the function’s browsers, and other
comments while quick dialogs
definition shows the
feature code and is
convenient.
6
Python and MySQL for Beginner

CRITERIA VS Code PyCharm IDLE

Need some extensions Built with Python in Can be extended with


to make your code mind, and available additional libraries and
editor like an IDE that extensions aimed at tools through the use of
fits well into Python. improving PyCharm. pip, the package
Detects the type of More than 3000 manager for Python.
Extensions
project you’re working JetBrains plugins are
on and then suggests available and
and embeds the compatible with all of
necessary extensions them.
for that project.

Database integration Uses a plugin called Need to install a


Database Integration available on VS Code Database Navigator that database driver for the
with the extension allows connecting to specific database you
called SQLTools. A databases like MySQL, are using (such as
beginner might find it Oracle, PostgreSQL, and psycopg2 for
difficult to use or others, all within the PostgreSQL or mysql-
navigate, and it can be app. Other than that, connector-python for
susceptible to bugs. you can create a MySQL). Once you have
database connection, the driver installed, you
issue queries to a can use the appropriate
database, receive library to connect to the
database objects, and database and perform
more. However, this is operations such as
only available in the querying and updating
professional version, data. You can also use
and must be purchased. an ORM (Object-
Relational Mapping)
library such as
SQLAlchemy to simplify
the process of
interacting with the
database.

7
Python and MySQL for Beginner

Minimum requirements for Visual Studio Code (VS Code)


installation

To install and run Visual Studio Code (VS Code) for Python development, your system
should meet the following minimum requirements:
1. Operating System: Windows 7 or later, macOS 10.10 or later, or Linux (64-bit)
2. Processor: 1.6GHz or faster, 2-core
3. Memory: 2 GB or more
4. Hard Disk Space: At least 1 GB of free space
5. Display: 1024x768 resolution or higher
6. Internet connection: Required for installation and updates
7. Administrator rights: Installation of VS Code requires administrator rights on Windows
and macOS.
8. Python: To use VS Code for Python development, you will need to have Python
installed on your system. You can download the latest version of Python from the
official website.
9. Python Extension for Visual Studio Code: In order to use VS Code for Python
development, you will need to install the Python extension for VS Code. This extension
provides rich support for Python development, including IntelliSense, debugging, and
linting.
10. A Python environment: Python can be used with virtual environments like Anaconda,
venv, virtualenv and pipenv.

Minimum requirements for PyCharm installation

PyCharm is a popular and widely used Integrated Development Environment (IDE) for
Python development developed by JetBrains. To install and run PyCharm, your system
should meet the following minimum requirements:
1. Operating System: Windows, macOS, or Linux
2. Processor: 2 GHz or faster
3. Memory: 2 GB of RAM or more
4. Hard Disk Space: At least 1 GB of free space
5. Display: 1024x768 resolution or higher
6. Internet connection: Required for installation and updates
7. Administrator rights: Installation of PyCharm requires administrator rights on Windows
and macOS.
8. Python: PyCharm is a Python IDE, so you will need to have Python installed on your
system. You can download the latest version of Python from the official website.
9. Java: PyCharm requires Java to be installed on your system. The latest version of Java
can be downloaded from the official website.
10. A Python environment: PyCharm can be used with virtual environments like Anaconda,
venv, virtualenv and pipenv.

You may need additional tools or libraries depending on the specific Python development tasks you plan to do. Be
sure to check the documentation for any libraries or frameworks you plan to use to ensure that your system meets
their requirements.

8
Python and MySQL for Beginner

Minimum requirements for IDLE installation

IDLE (Integrated Development and Learning Environment) is the default, built-in Python
development environment that comes with Python. The requirements to install and run
IDLE are as follows:
1. Operating System: Windows, macOS, or Linux
2. Python: IDLE is built into Python, so you will need to have Python installed on your
system. You can download the latest version of Python from the official website.
3. Memory: IDLE is a lightweight development environment, so it does not require a large
amount of memory to run.
4. Display: IDLE requires a minimum resolution of 1024x768 or higher.
5. Internet connection: Not required for IDLE installation as it comes with Python
installation itself.
6. Administrator rights: IDLE does not require administrator rights to install or run.
7. A Python environment: IDLE can be used with virtual environments like Anaconda,
venv, virtualenv and pipenv.

As IDLE is already included with the Python installation, there is no need to install it
separately. You just need to open the terminal or command prompt and type python -m
idlelib to open IDLE.

Please note that IDLE is a basic text editor and does not have some of the features of
advanced IDEs like PyCharm, visual studio code, etc. It's best suited for beginners or small
scale projects.

9
Python and MySQL for Beginner

Laragon

Provides a fast and easy way to spin up an


isolated Windows development (like a Virtual
Machine, it doesn’t touch your OS). Users can
The first version of Laragon was released in install it as a software, start it up, do their
2016 and was primarily focused on providing a programming, and just exit when finished. The
simple and lightweight package for setting up a platform comes pre-installed with many popular
local web development environment applications like Node.

Portable, isolated, fast & powerful universal Built from the ground up for ease
development environment for PHP, Node. js, of use and perfect compatibility
Python, Java, Go, Ruby. It is fast, lightweight, with Laravel.
easy-to-use and easy-to-extend. Great for
building and managing modern web applications.

Before installing Laragon, here are a few things you should be aware of:
1. System Requirements: Laragon requires Windows 7 or later, and at least 1 GB of RAM.
2. Disk Space: Make sure you have enough disk space to install Laragon and any
projects you plan to work on.
3. Firewall: If you have a firewall enabled, you may need to configure it to allow Laragon
to access the internet and connect to other services.
4. Anti-virus: Some anti-virus software may interfere with the installation or operation of
Laragon. Make sure to temporarily disable your anti-virus software before installing
Laragon, and add an exception for it if needed.
5. Existing Installation: If you have an existing web server, PHP, or MySQL installation,
you may need to remove it or reconfigure it before installing Laragon.
6. Backup: It's always a good idea to make a backup of any important files or data before
making any changes to your system, in case something goes wrong during the
installation.
7. Familiarize yourself with the tools: To get the most out of Laragon, it's a good idea to
be familiar with the tools it includes, such as Apache, PHP, and MySQL, so that you can
configure and troubleshoot them as needed.

By following these steps, it should make the installation process of Laragon smoother and
avoid any potential issues.

10
CHAPTER 3
INSTALLING PYTHON
AND
IDE ENVIRONMENT SETUP

11
Python and MySQL for Beginner

01
Python installation. Go to Figure 1 (https://www.python.org/)
and download the latest version of Python. Follow the
instructions by scan the QR Code.

After installing, you can run Python Interpreter by type IDLE in


search Windows and press enter (Figure 2). An IDLE Shell will
appear. You can type your coding here (Figure 3). Source: YouTube

Figure 1: Python.org

Figure 3: IDLE Shell

12
Figure 2: Search IDLE
Python and MySQL for Beginner

02
IDE Installation for Visual Studio Code. Go to Figure 4
(https://code.visualstudio.com/Download) and download the suitable
version with your machine. Follow the instructions on How to install
Visual Studio Code on Windows 10/11 [2022 Update] Complete Guide
by scan the QR Code.

Interface VSCode Figure 5. You can start coding here.

Source: YouTube

Figure 4: Download Visual


Studio Code - Mac, Linux,
Windows

Figure 5: Interface VSCode

13
Python and MySQL for Beginner

03
IIDE Installation for PyCharm. Go to Figure 6
(https://www.jetbrains.com/pycharm/download/#section=window
s) and download the Community version. Follow the instructions
on Install Python 3.10 and PyCharm on Windows 10 by scan the
QR Code.

Interface PyCharm Figure 7. You can start coding here. For


PyCharm users, if the module involves different projects the Source: YouTube
module installation needs to be done each time.

Figure 6: Download
PyCharm: Python IDE for
Professional Developers
by JetBrains

Figure 7: Interface PyCharm

14
Python and MySQL for Beginner

04
Command prompt application needs.

Three steps to check the Python version on your Windows


operating system.
1. Open the command prompt application: Press the Windows
key to open the start screen. In the search box type
"command". Click on the command prompt application as
Figure 8.
2. Execute command: type python --version and press enter.
3. The Python version appears in the next line right below your
command.

Figure 8: Interface Command


Prompt

05
Web server installation for Laragon. Go to Figure 9
(https://laragon.org/download/), download Laragon - Full (173 MB).
Follow the instructions for complete installation.

Figure 9: Download | Laragon - portable,


isolated, fast & powerful universal
development environment for PHP, Node.js,
Python, Java, Go, Ruby.

15
CHAPTER 4
FIRST PROJECT ACTIVITY

16
Python and MySQL for Beginner

Set up local web server Laragon

01
Right click Start All > Click MySQL > Click MySQL (Figure 10)

Figure 10: Start up MySql

Click database as Figure 11.

Figure 11: Click Database

17
Python and MySQL for Beginner

Session manager window will appear. Click New. Please make sure the port is
correct, user (usually root) with password (usually empty), then click open

01
(Figure 12)

Figure 12: Session Manager

The screen will appear as Figure 13. db1 (database name) and table1(table
name). If you want rename -> right-click the database or table name > rename.
Press F5 for refresh table or database. If user want to see the data of the
table, user need to click selected table > Click data.

Figure 13: Database Interface

18
Python and MySQL for Beginner

Choose your favourite IDE either PyCharm or VSCode.


Those IDE use different database configuration.

PyCharm User Configuration into database

Create a new project named PythonAndMysql.

02
Click Icon Setting > select Setting or used shortcut key Ctrl+ Alt + S (Figure 14).

Figure 14: Settings

Pop window will appear.

Expand Project: PythonAndMysql and choose Python Interpreter (Figure 15).

Figure 15: Settings PyCharm window

19
Python and MySQL for Beginner

Python Interpreter interface will be shown. Here we will install a specific


module name: mysql.connector. This action can be done by click in plus icon
(+) or use shortcut key Alt + Insert (Figure 16)

02

Figure 16: Add module

Search mysql-connector-python on the search field click Install Package.


Please be sure that you have an internet connection, since you are installing a
package from the cloud. (Figure 17)

Figure 17: Available Packages window

20
Python and MySQL for Beginner

If installation is successful a green bar will appear with a message stating that
the installation is successful. Please try again if not successful. Close the
python interpreter pop up screen and head to the code editor interface.
(Figure 18).

02 Figure 18: Package installed successfully

File name main.py is the default fail that will be run by the PyCharm (Figure 19).

Figure 19: Default file

VSCode User Configuration into database

1. Open the command prompt application: Press the Windows key to open the
start screen. In the search box type "command". Click on the command
prompt application.
2. Execute command: type pip install mysql-connector-python and press enter.
3. The advantage of using VSCode, the user only needs to install it once and
the module can be used by any Python project.

Figure 20: Interface Command Prompt for mysql-connector-python module


installation

21
Python and MySQL for Beginner

Requirement mysql.connector installation into database.

MySQL is a Relational Database Management System (RDBMS) whereas the structured Query
Language (SQL) is the language used for handling the RDBMS using commands i.e Creating,
Inserting, Updating and Deleting the data from the databases. SQL commands are case
insensitive i.e CREATE and create signify the same command.

MySQL Connector/Python enables Python programs to access MySQL databases, using an API
that is compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure
Python and does not have any dependencies except for the Python Standard Library.

Basic Python keywords do you need to know.

connect: to make a connection to the database, all credentials


such as username, server name, server password and database
name need to be specified.

error: This is exception cursor: to help our program


handling, if there are any issues, execute SQL command/ operation
it will be included in this Error (can be renamed using "as"
method)

22
Python and MySQL for Beginner

In this activity:

You will build a program with Create Read Update Delete (CRUD) method.

Your program will display 10 menu (Figure 21).

Each menu has it owns specific task. User can choose any menu even
there is no database has been created.

You will create your own specific module and submodule.

You will build your own function from scratch to fill in the selected menu.

Use conditional structure to display the menu.

03 Write the code and observe the output for each menu.

Figure 21: Program Menu

23
Python and MySQL for Beginner

Let's try the activity

Create module

Create your own module, name it as moduleDB in your directory with four(4)
submodules (Figure 22):
deleteData.py
displayData.py
insertData.py
updateData.py

Your main program is main.py.

Figure 22: List file in PythonAndMysql directory

24
Python and MySQL for Beginner

Now, move to ModuleDb directory to complete our submodules

1 Create insertData.py

import mysql.connector

# insert data into table


def insert(host, username, password, database, table_name):
try:
db = mysql.connector.connect(
host=host,
user=username,
password=password,
database=database
)

# A display to insert data


id = input("Enter Lecturer Id : ")
fname = input("Enter Lecturer First Name : ")
lname = input("Enter Lecturer Last Name : ")
age = input("Enter Age : ")
phone_num = input("Enter Phone Number : ")
department = input("Enter Department : ")

cursor = db.cursor()
sql = "insert into " + table_name + "(id, fname, lname, age,
phone_num, department) values(%s, %s, %s, %s, %s, %s)"
print(sql)

val = (id, fname, lname, age, phone_num, department)


cursor.execute(sql, val)
db.commit()
# For a connection obtained from a connection pool,
# close() does not actually close it but returns it to the pool
# and makes it available for subsequent connection requests.
db.close()
print('One record inserted into ' + table_name)

except:
# .rollback method sends a ROLLBACK statement to the MySQL
server,
# undoing all data changes from the current transaction.
# By default, Connector/Python does not autocommit,
# so it is possible to cancel transactions when using
transactional storage engines such as InnoDB.
db.rollback()

25
Python and MySQL for Beginner

2 Create deleteData.py

import mysql.connector

# delete data in table


def delete(host, username, password, database, table_name):
print("")

# The connect() constructor creates a connection to the MySQL


server and returns a MySQLConnection object
db = mysql.connector.connect(
host=host,
user=username,
password=password,
database=database
)

# .cursor method returns a MySQLCursor() object, or a subclass of


it depending on the passed arguments.
# The returned object is a cursor.
cursor = db.cursor()
sql_Delete_query = "Delete from "+table_name+" where id = %s"
Id = input('Enter lecturer id : ')
# .execute method executes the given database operation (query or
command)
cursor.execute(sql_Delete_query, (Id,))

# This method sends a COMMIT statement to the MySQL server,


# committing the current transaction.
# Since by default Connector/Python does not autocommit,
# it is important to call this method after every transaction
# that modifies data for tables that use transactional storage
engines.
# https://dev.mysql.com/doc/connector-python/en/connector-python-
api-mysqlconnection-commit.html
db.commit()
print("One row(s) deleted from "+table_name)

26
Python and MySQL for Beginner

3 Create displayData.py

import mysql.connector

# display data
def displayTableInfromation(host, username, password, database,table_name):

# The connect() constructor creates a connection to the MySQL server and


returns a MySQLConnection object
db = mysql.connector.connect(
host=host,
user=username,
password=password,
database=database
)

# .cursor method returns a MySQLCursor() object, or a subclass of it


depending on the passed arguments.
# The returned object is a cursor.
cursor = db.cursor()

# Reports whether the connection to MySQL Server is available.


if db.is_connected():

# .execute method executes the given database operation (query or


command)
cursor.execute("SELECT * FROM "+table_name)

# row is just a variable.


# this variable will print every column for each row of data.
for row in cursor:
print("\nLecturer ID : ", row[0])
print("First Name : ", row[1])
print("Last Name : ", row[2])
print("Age : ", row[3])
print("Phone Number : ", row[4])
print("Department : ", row[5])

27
Python and MySQL for Beginner

4 Create updateData.py

import mysql.connector

# update data into table


def update(host, username, password, database, table_name):
db = mysql.connector.connect(
host=host,
user=username,
password=password,
database=database
)
id = input("Enter Lecturer Id : ")
fname = input("Enter Lecturer First Name : ")
lname = input("Enter Lecturer Last Name : ")
age = input("Enter Age : ")
phone_num = input("Enter Phone Number : ")
department = input("Enter Department : ")

cursor = db.cursor()
try:
sqlFormula = "UPDATE "+table_name+" SET fname = %s WHERE id = %s"
cursor.execute(sqlFormula, (fname, id))

sqlFormula = "UPDATE "+table_name+" SET lname = %s WHERE id = %s"


cursor.execute(sqlFormula, (lname, id))

sqlFormula = "UPDATE "+table_name+" SET age = %s WHERE id = %s"


cursor.execute(sqlFormula, (age, id))

sqlFormula = "UPDATE "+table_name+" SET phone_num = %s WHERE id = %s"


cursor.execute(sqlFormula, (phone_num, id))

sqlFormula = "UPDATE "+table_name+" SET department = %s WHERE id = %s"


cursor.execute(sqlFormula, (department, id))

db.commit()

print("entries updated in " + table_name)

except:
db.rollback()

5 Run and observe the output.

28
Python and MySQL for Beginner

01 Import module in main.py


# import mysql.connector with specified submodule to be use: connect,
Error and cursor
from mysql.connector import connect, Error, cursor

# import our own module moduleDB and specified submodule insertData,


updateData, deleteData and displayData
# The "as" keyword is used to create an alias
from moduleDB import insertData as insert, updateData as update,
deleteData as delete, displayData as display

02 Create database function in main.py


# function 1: create new database
def create_db(username, password):
try: # try block lets you test a block of code for errors
with connect(
# "host" is server name / targeted server to be connected
host=glbHost,
user=username,
password=password
) as connection:
dbname = input("What is DB name you want to create? ")
create_db_query = "CREATE DATABASE "+dbname
print(create_db_query)
with connection.cursor() as cursor:
cursor.execute(create_db_query)
print("Database "+dbname+" is created!")
# except block lets you handle the error
except Error as e:
print("Opss, something is wrong", e)
# NameError raised when a variable is not found in local or global
scope.
except NameError:
print("NameError is raised when the identifier being accessed is
not defined in the local or global scope.")

29
Python and MySQL for Beginner

03 Drop database function in main.py


# function 2: delete database
def drop_db(username, password):
try:
# database connection
# set all database credential (host,user, password)
with connect(
host=glbHost,
user=username,
password=password
)as connection:
dbname = input("What is DB name you want to drop?: ")
drop_db_query = "DROP DATABASE %s" % dbname
with connection.cursor() as cursor:
cursor.execute(drop_db_query)
print('Database ', dbname, ' has been dropped.')

except Error as e:
print(format(e))

04 Create table function in main.py


# function 3: create new table
def create_table(username, password):
dbName = input('Enter database name first: ')
try:
# database connection
# set all database credential (host,user, password, database)
with connect(
host=glbHost,
user=username,
password=password,
database=dbName
) as connection:
table_name = input('insert table name you want to crete: ')
create_table_query = "CREATE TABLE "+table_name+"
(id INT AUTO_INCREMENT PRIMARY KEY, fname VARCHAR(50), " \
"lname VARCHAR(50), age INT, phone_num VARCHAR(100), " \
"department VARCHAR(100)) "
print(create_table_query)
with connection.cursor() as cursor:
cursor.execute(create_table_query)

for x in cursor:
print(x)
except Error as e:
print(format(e))

30
Python and MySQL for Beginner

05 Drop table function in main.py


# function 4: delete table
def drop_table(username, password):
dbName = input('From which database you want to delete the table?: ')
try:
# database connection
# set all database credential (host,user, password, database)
with connect(
host=glbHost,
user=username,
password=password,
database=dbName
) as connection:
dbtable = input('Enter table name : ')
drop_table_query = "DROP Tables " + dbtable
print(drop_table_query)
with connection.cursor() as cursor:
cursor.execute(drop_table_query)
print('Table', dbtable, 'has been dropped.')
except Error as e:
print(format(e))

06 Display all databases function


# function 5: display all database existed
def show_database(username, password):
try:
# database connection
# set all database credential (host,user, password)
with connect(
host=glbHost,
user=username,
password=password
) as connection:
cursor = connection.cursor()
databases = ("show databases")
cursor.execute(databases)
i = 0
for (databases) in cursor:
i = i+1
print("Database ",i ,"is :", databases[0])
except Error as e:
print("Opss, something is wrong", e)
except NameError:
print("NameError is raised when the identifier being accessed is not
defined in the local or global scope.")

31
Python and MySQL for Beginner

07 Finish the whole program


# display text
print("**********POLYTECHNIC MERSING DATABASE**********")
print("1. CREATE DATABASE \n2. DROP DATABASE \n3. CREATE TABLE "
"\n4. DROP TABLE \n5. INSERT \n6. UPDATE \n7. DELETE "
"\n8. DISPLAY \n9. SHOW DATABASE \n10. EXIT\n")
while True:
choice = input("Enter your choice :")
if choice in ('1', '2', '3', '4', '5', '6', '7', '8', '9'):

# glbHost is a global variable for "localhost"


# "localhost" is the targeted server to be connected
glbHost = "localhost"
u = input("Enter Mysql Username: ")
p = input("Enter Mysql Password: ")
i = 0

if choice == '1':
# go create_db function
create_db(u, p)

elif choice == '2':


# go to drop_db function
drop_db(u, p)

elif choice == '3':


# go to create_table function
create_table(u, p)

elif choice == '4':


# go to drop_table function
drop_table(u, p)

elif choice == '5':


database = input("Enter database name: ")
table_name = input("Enter table name: ")
# go to moduleDB insertData.py
insert.insert(glbHost, u, p, database, table_name)

elif choice == '6':


database = input("Enter database name: ")
table_name = input("Enter table name: ")
# go to moduleDB updateData.py
update.update(glbHost, u, p, database, table_name)

elif choice == '7':


database = input("Enter database name: ")
table_name = input("Enter table name: ")
# go to moduleDB deleteData.py
delete.delete(glbHost, u, p, database, table_name)

elif choice == '8':


database = input("Enter database name: ")
table_name = input("Enter table name: ")
# go to moduleDB deleteData.py
display.displayTableInfromation(glbHost, u, p, database,
table_name)

elif choice == '9':


# go to show_database function
show_database(u, p)

elif choice == '10':


exit()
else:
print("Invalid Input ")

32
Python and MySQL for Beginner

References

Akhter, M. (2022, January 11). How to install Visual Studio Code on Windows 10/11 [2022 Update] Complete
Guide [Video]. YouTube. https://www.youtube.com/watch?v=JPZsB_6yHVo

Ansgar, B. (n.d.). HeidiSQL. Retrieved from https://www.heidisql.com/

Computer Science. (2021, November 13). Install Python 3.10 and PyCharm on Windows 10 [Video].
YouTube. https://www.youtube.com/watch?v=WJynvGY-2wk

Downey, A. (n.d.). Introduction to GUI programming. Python Textbook. Retrieved from https://python-
textbok.readthedocs.io/en/1.0/Introduction_to_GUI_Programming.html

GeeksforGeeks. (n.d.). MySQL-Connector-Python module in Python. Retrieved from


https://www.geeksforgeeks.org/mysql-connector-python-module-in-python/

JetBrains. (n.d.). PyCharm download. Retrieved from


https://www.jetbrains.com/pycharm/download/#section=windows

Laragon. (n.d.). Laragon - portable, isolated, fast & powerful universal development environment for PHP,
Node.js, Python, Java, Go, Ruby. Retrieved from https://laragon.org/download/

Microsoft. (n.d.). Visual Studio Code download. Retrieved from https://code.visualstudio.com/Download

Ngo, J. (2021, February 3). PyCharm vs. VS Code: Which is the better code editor? [Blog post]. LogRocket.
https://blog.logrocket.com/pycharm-vs-
vscode/#:~:text=PyCharm%20and%20VS%20Code%20are,to%20an%20IDE%20through%20extensions.

Oracle Corporation. (n.d.). MySQL Connector/Python Developer Guide. Retrieved from


https://dev.mysql.com/doc/connector-python/en/

Python Software Foundation. (n.d.). IDLE. Python 3 documentation. Retrieved from


https://docs.python.org/3/library/idle.html

Python Software Foundation. (n.d.). Python. Retrieved from https://www.python.org/

Santos, A. (2021, November 5). How to Install Python 3.10.2 on Windows 10 [Video]. YouTube.
https://www.youtube.com/watch?v=uKHVNKd3f20

Sid Martin Biotechnology Institute. (n.d.). What is Laragon used for? Retrieved from
https://www.sidmartinbio.org/what-is-laragon-used-for/

Srinivasan, S. (2019, December 3). PyCharm vs VS Code. Tangent Technologies.


https://tangenttechnologies.ca/blog/pycharm-vs-vscode/

33
POLITEKNIK MERSING
Jalan Nitar,
86800 Mersing
Johor Darul Ta’zim
Telephone : 07-7980001
Fax : 07-7980002
Website : https://pmj.mypolycc.edu.my/

You might also like