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

Fitness Tracker(Adithya)[1]

Uploaded by

harissh 07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

Fitness Tracker(Adithya)[1]

Uploaded by

harissh 07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

COMPUTER SCIENCE PROJECT

(2024-2025)
PROJECT TITLE: FITNESS TRACKER MANAGEMENT

ROLL NO:
NAME:

CLASS: XII ‘B’


SUBJECT: COMPUTER SCIENCE
SUB CODE: 083

PROJECT GUIDE: Mrs. Sujith Mary.V


PGT (CS)
THE PIONEER SCHOOL, CBSE
NAGERCOIL
TAMIL NADU
CERTIFICATE

This is to certify that cadet ____________________ Roll no:


________________ has successfully completed the project work entitled
Fitness Tracker Management in the subject COMPUTER SCIENCE
(083) laid down in the regulation of CBSE for the purpose of Practical
Examination in Class XII to be held in THE PIONEER SCHOOL on
_____________.

(V.Sujith Mary)
PGT Comp Science

INTERNAL EXAMINER EXTERNAL EXAMINER

PRINCIPAL
CONTENTS

S.NO DESCRIPTION PG NO

1. ACKNOWLEDGEMENT 1

2. INTRODUCTION 2-12

3. SOURCE CODE 13-18

4. OUTPUT 19-25

5. PURPOSE OF TESTING 26-27

6. SOFTWARE, HARDWARE REQUIREMENTS 28-33

7. USE OF TECHNOLOGY 30-33

8. BIBLIOGRAPHY 34
ACKNOWLEDGEMENT

We are grateful to our respectable teacher, Mrs.SUJITH MARY ma’am


who has been instrumental in guiding us through this project successfully.
With her wisdom and knowledge, we were able to complete this report with
ease under his supervision which was a very enriching experience for all of
us!
We also would like to thank our parents whose advice helped us make the
production process much smoother and easier than expected considering it
was such an ambitious task from the start!
Lastly, without their help along the way, I’m not sure if we could have made
it here today so thanks go out as well to everyone else that contributed at
some point or another during our journey on completing this remarkable

undertaking together.

1
INTRODUCTION

In today's fast-paced world, maintaining a healthy lifestyle has become


increasingly important. A fitness tracker is an essential tool that helps
individuals monitor their physical activities, track progress, and set
health goals. This project aims to develop a fitness tracker using
Python, with a focus on file handling for storing, updating, and
retrieving user data.

In this project, users will be able to log their daily workouts, record key
fitness metrics like calories burned, and exercise duration. The data
will be stored in a text file, allowing for easy access and management
of user records over time. The fitness tracker will feature the ability to:

 Add new fitness entries (e.g., type of exercise, duration, calories


burned).

 View previously logged data to track progress.

 Edit or delete entries as needed.

File handling is central to this project as it enables the application to


persistently store user data, which can be retrieved and modified later.
By using Python's file handling capabilities, we ensure that user
progress is tracked efficiently without the need for complex databases.
This approach not only makes the project beginner-friendly but also
showcases how Python's file input/output operations can be applied in a
real-world application.

2
Key Features of the Fitness Tracker Program:

1. Log Exercise:

Allows users to log exercise details such as exercise type,


duration, calories burned, steps taken, and the date. This data
is stored in a text file for easy tracking.
2. View Exercise Log:

Displays a comprehensive list of all logged exercises. Each


entry includes the exercise name, duration, calories burned,
steps, and the date of the activity.
3. Calculate Total Calories Burned:

Automatically sums up the total calories burned from all


logged exercises. This feature helps users track their overall
calorie expenditure.
4. Calculate Total Duration:

Calculates and displays the total time spent on exercises,


providing users with an overview of their total workout
duration.
5. View Exercise Statistics:

Provides key statistics including total calories burned, total


exercise duration, total steps taken, and the number of
exercises. It also displays averages for each category to give a
deeper analysis of the user’s fitness activities.

3
6. Delete Exercise Log:

Allows users to completely clear the exercise log, deleting all


recorded entries. Useful for starting fresh or resetting the data.
7. Search Exercise Log:

Users can search for specific exercises or keywords in their


log. The program returns all matching entries based on the
search term, making it easy to find specific records.
8. Sort Exercise Log:

The exercise log can be sorted alphabetically by the exercise


name, which helps keep the entries organized and easy to
navigate.
9. Update Exercise Log:

Users can update or modify existing exercise records by


specifying the exercise to be updated. This feature helps to
correct or revise previous entries in the log.
10. Calculate Total Steps:

The program calculates the total number of steps taken across


all logged exercises. Useful for tracking step-based fitness
goals.
11. Exit Program:

The user can safely exit the program, saving all exercise data
before the program closes.

4
SYSTEM DEVELOPMENT LIFE CYCLE (SDLC)

The system development life cycle is a project management


technique that divides complex into smaller, more easily management
segments or phases. Segmenting projects allows managers to verify the
successful completion of project phases before allocating resources to
subsequent phases.
Software development projects typically include initiation, planning,
design, development and maintenance phases or initiation, concept
development and planning phases. End users of the system under
development should be involved interviewing the output of each phase to
ensure the system is being built to deliver the needed functionality.

5
PHASES OF SYSTEM DEVELOPMENT LIFE
CYCLE

INITIATION PHASE:

● The Initiation Phase begins when a business sponsor identifies a need or


an opportunity.
● Identify and validate an opportunity to improve business
accomplishment
● The purpose of the initiation phase is to:of the organization or a
deficiency related to a business need.
● Identify significant assumptions and constraints on solutions to that
need.
● Recommend the explorations of alternative concepts and methods to
satisfy the need including questioning the need for technology i.e.., will a
change in the business process offer a solution?
● Assure executive business and executive technical sponsorship. The
Sponsor designates a Project Manager and the business need is documented in
a concept proposal. The concept proposal includes information about the
business process and the relationship to the Agency/Organization.

ANALYSIS STAGE:

Once the planning is done, it’s time to switch to the research and analysis
stage.
In this step, you incorporate more specific data for your new system. This
includes the first system prototype drafts, market research, and an evaluation
of competitors.
6
To successfully complete the analysis and put together all the critical
information for a certain project, developers should do the following:
Generate the system requirements. A Software Requirement Specification
(SRS) document will be created at this stage.
Your DevOps team should have a high degree of input in determining the
functional and network requirements of the upcoming project.Evaluate
existing prototypes. Different prototypes should be evaluated to identify those
with the greatest potential. Conduct market research. Market research is
essential to define the pains and needs of end-consumers. In recent years,
automated NLP (natural language processing) research has been undertaken to
glean insights from customer reviews and feedback at scale. Set concrete
goals. Goals are set and allocated to the stages of the system development life
cycle. Often, these will correspond to the implementation of specific features.
Most of the information generated at this stage will be contained in the SRS.
This document shapes the strict regulations for the project and specifies the
exact software model you will eventually implement.

DESIGN STAGE:

The next stage of a system development project is design and prototyping.


This process is an essential precursor to development. It is often incorrectly
equated with the actual development process but is rather an extensive
prototyping stage.
This step of the system development life cycle can significantly eliminate the
time needed to develop the software. It involves outlining the following:
 The system interface
 Databases
 Core software features (including architecture like microservices)
7
 User interface and usability
 Network and its requirement
As a rule, these features help to finalize the SRS document as well as create
the first prototype of the software to get the overall idea of how it should look
like.
Prototyping tools, which now offer extensive automation and AI features,
significantly streamline this stage.

DEVELOPMENT STAGE:
In the development stage of SDLC, the system creation process produces a
working solution. Developers write code and build the app according to the
finalized requirements and specification documents.
This stage includes both front and back-end development. DevOps engineers
are essential for allocating self-service resources to developers to streamline
the process of testing and rollout, for which CI/CD is typically employed.
This phase of the system development life cycle is often split into different
sub-stages, especially if a microservice or miniservice architecture, in which
development is broken into separate modules, is chosen.
Developers will typically use multiple tools, programming environments, and
languages (C++, PHP, Python, and others), all of which will comply with the
project specifications and requirements outlined in the SRS document.

8
Benefits of Fitness Tracker Management:

The Fitness Tracker Management system offers numerous benefits, making it


an invaluable tool for individuals looking to lead healthier and more active
lifestyles. With increasing awareness of the importance of fitness and well-
being, the system plays a pivotal role in empowering users to take charge of
their physical health. The core advantage of the fitness tracker lies in its
ability to collect, store, and analyse data related to physical activities,
providing users with meaningful insights into their habits and progress.

One of the most significant benefits of the system is the enhancement of


health awareness. In a world where sedentary lifestyles and unhealthy habits
are prevalent, having a system that actively monitors fitness activities can be
transformational. Users are prompted to record their daily exercises, including
details such as type, duration, and intensity, which fosters a greater
understanding of their physical routines. This habit of recording activities
cultivates self-discipline and motivates individuals to stay consistent in their
efforts to maintain an active lifestyle.

The system is also instrumental in helping users set realistic fitness goals and
track their progress. By consistently logging their activities, users can identify
patterns in their behaviour and assess whether they are meeting their fitness
objectives. For instance, the application’s ability to calculate total calories
burned, total steps taken, and average duration of exercises enables users to
monitor their overall performance. Over time, these insights help individuals
make informed adjustments to their routines, ensuring they remain aligned
with their goals. Whether someone is striving to lose weight, improve
cardiovascular health, or build muscle, the system offers a structured

9
approach to tracking progress and maintaining accountability.

Another critical advantage of the Fitness Tracker Management system is its


ability to provide data-driven insights through comprehensive analysis and
reporting. The application’s analytical tools transform raw data into
actionable information, empowering users to understand the impact of their
efforts. For example, the system generates weekly and monthly reports that
summarize key metrics such as total calories burned and average steps taken.
These reports are instrumental in helping users visualize their achievements
and identify areas for improvement. Such data not only fosters a sense of
accomplishment but also motivates users to maintain or enhance their
performance.

Moreover, the system’s simplicity and user-friendly design ensure that


individuals from all walks of life can use it effectively. Unlike sophisticated
wearable devices that may require technical expertise, the Fitness Tracker
Management system is designed with accessibility in mind. The intuitive
interface ensures that users can quickly log activities, retrieve data, and
interpret reports without extensive training. This simplicity makes it an ideal
choice for beginners who may be intimidated by more complex fitness tools,
as well as for experienced users seeking a reliable solution for tracking their
activities.

Beyond its immediate benefits for individuals, the system has a broader
societal impact by promoting healthier communities. Encouraging users to
adopt regular exercise routines contributes to reducing the prevalence of
lifestyle-related diseases such as obesity, diabetes, and hypertension. The
ability to track progress and visualize improvements instills a sense of
10
responsibility and pride, encouraging users to share their success stories with
others. This ripple effect can inspire friends, family, and colleagues to
prioritize their own health, creating a positive feedback loop of well-being
and motivation within communities.

The Fitness Tracker Management system also offers a high degree of


customization, which is essential for catering to diverse user needs. People
engage in different types of physical activities, from walking and running to
strength training and yoga. The system accommodates this diversity by
allowing users to log various types of exercises and tailor their fitness goals to
their unique preferences and lifestyles. This flexibility ensures that the
application remains relevant and valuable to a wide range of users, regardless
of their fitness level or objectives.

Additionally, the system’s ability to manage data efficiently makes it an


excellent tool for long-term tracking and trend analysis. By maintaining a
digital log of activities, users can look back at their progress over weeks,
months, or even years. This historical data is invaluable for identifying long-
term trends and making strategic decisions about fitness regimens. For
instance, users can pinpoint periods of high productivity or identify setbacks,
enabling them to learn from their experiences and improve their future
performance.

11
FLOW CHART:

12
Source code:
import mysql.connector as sql
from datetime import datetime

# Connect to the database


def connect_to_database():
try:
conn = sql.connect(host='localhost',
user='root', passwd='password',
database='fitness_tracker')
if conn.is_connected():
print("Connected to the database
successfully.")
return conn
except sql.Error as e:
print(f"Error connecting to the database: {e}")
return None

# Display menu
def display_menu():
print("\nFitness Tracker Menu:")
print("1. Log Exercise")
print("2. View Exercise Log")
print("3. Calculate Total Calories Burned")
print("4. Calculate Total Duration")
print("5. View Exercise Statistics")
print("6. Delete Exercise Log")
print("7. Search Exercise Log")
print("8. Sort Exercise Log")
print("9. Update Exercise Log")
print("10. Calculate Total Steps")
print("11. Exit")
print("\n")

# Log exercise
def log_exercise(cur):
try:
exercise = input("Enter exercise (e.g.,
'jogging', 'weightlifting', etc.): ")
duration = float(input("Enter duration (in
minutes): "))
calories_burned = float(input("Enter calories
burned: "))
steps = int(input("Enter steps taken: "))
13
date = input("Enter date (YYYY-MM-DD): ")

query = "INSERT INTO exercise_log (exercise,


duration, calories_burned, steps, date) VALUES (%s,
%s, %s, %s, %s)"
cur.execute(query, (exercise, duration,
calories_burned, steps, date))
print("Exercise logged successfully!\n")
except Exception as e:
print(f"Error logging exercise: {e}\n")

# View exercise log


def view_exercise_log(cur):
try:
cur.execute("SELECT * FROM exercise_log")
rows = cur.fetchall()

if rows:
print("\nExercise Log:")
for row in rows:
print(f"Exercise: {row[1]}, Duration:
{row[2]} minutes, Calories Burned: {row[3]}, Steps:
{row[4]}, Date: {row[5]}")
else:
print("No exercises logged yet.\n")
except Exception as e:
print(f"Error fetching exercise log: {e}\n")

# Calculate total calories burned


def calculate_total_calories_burned(cur):
try:
cur.execute("SELECT SUM(calories_burned) FROM
exercise_log")
total_calories = cur.fetchone()[0] or 0
print(f"Total Calories Burned: {total_calories}\
n")
except Exception as e:
print(f"Error calculating total calories burned:
{e}\n")

# Calculate total duration


def calculate_total_duration(cur):
try:
cur.execute("SELECT SUM(duration) FROM
exercise_log")
14
total_duration = cur.fetchone()[0] or 0
print(f"Total Duration: {total_duration}
minutes\n")
except Exception as e:
print(f"Error calculating total duration: {e}\
n")

# View exercise statistics


def view_exercise_statistics(cur):
try:
cur.execute("SELECT COUNT(*),
SUM(calories_burned), SUM(duration), SUM(steps) FROM
exercise_log")
stats = cur.fetchone()

if stats[0] > 0:
print(f"\nNumber of Exercises: {stats[0]}")
print(f"Total Calories Burned: {stats[1]}")
print(f"Total Duration: {stats[2]} minutes")
print(f"Total Steps: {stats[3]}")
print(f"Average Calories Burned per
Exercise: {stats[1] / stats[0]:.2f}")
print(f"Average Duration per Exercise:
{stats[2] / stats[0]:.2f} minutes")
print(f"Average Steps per Exercise:
{stats[3] / stats[0]:.2f}\n")
else:
print("No exercises logged yet.\n")
except Exception as e:
print(f"Error fetching exercise statistics: {e}\
n")

# Delete exercise log


def delete_exercise_log(cur):
try:
cur.execute("DELETE FROM exercise_log")
print("Exercise log deleted successfully!\n")
except Exception as e:
print(f"Error deleting exercise log: {e}\n")

# Search exercise log


def search_exercise_log(cur):
try:
search_term = input("Enter search term:
").lower()
15
query = "SELECT * FROM exercise_log WHERE
LOWER(exercise) LIKE %s"
cur.execute(query, (f"%{search_term}%",))
rows = cur.fetchall()

if rows:
print("\nSearch Results:")
for row in rows:
print(f"Exercise: {row[1]}, Duration:
{row[2]} minutes, Calories Burned: {row[3]}, Steps:
{row[4]}, Date: {row[5]}")
else:
print("No exercises found matching the
search term.\n")
except Exception as e:
print(f"Error searching exercise log: {e}\n")

# Sort exercise log


def sort_exercise_log(cur):
try:
cur.execute("SELECT * FROM exercise_log ORDER BY
exercise ASC")
rows = cur.fetchall()

if rows:
print("\nSorted Exercise Log:")
for row in rows:
print(f"Exercise: {row[1]}, Duration:
{row[2]} minutes, Calories Burned: {row[3]}, Steps:
{row[4]}, Date: {row[5]}")
else:
print("No exercises logged yet.\n")
except Exception as e:
print(f"Error sorting exercise log: {e}\n")

# Update exercise log


def update_exercise_log(cur):
try:
exercise_to_update = input("Enter the exercise
you want to update: ").lower()
cur.execute("SELECT * FROM exercise_log WHERE
LOWER(exercise) = %s", (exercise_to_update,))
row = cur.fetchone()

if row:
16
print(f"\nCurrent entry: Exercise: {row[1]},
Duration: {row[2]} minutes, Calories Burned: {row[3]},
Steps: {row[4]}, Date: {row[5]}")
exercise = input("Enter updated exercise: ")
duration = float(input("Enter updated
duration (in minutes): "))
calories_burned = float(input("Enter updated
calories burned: "))
steps = int(input("Enter updated steps
taken: "))
date = input("Enter updated date (YYYY-MM-
DD): ")
query = "UPDATE exercise_log SET exercise=
%s, duration=%s, calories_burned=%s, steps=%s, date=%s
WHERE id=%s"
cur.execute(query, (exercise, duration,
calories_burned, steps, date, row[0]))
print("Exercise updated successfully!")
else:
print("No matching exercise found.\n")
except Exception as e:
print(f"Error updating exercise log: {e}\n")

# Calculate total steps


def calculate_total_steps(cur):
try:
cur.execute("SELECT SUM(steps) FROM
exercise_log")
total_steps = cur.fetchone()[0] or 0
print(f"Total Steps Taken: {total_steps}\n")
except Exception as e:
print(f"Error calculating total steps: {e}\n")

# Main function
def main():
conn = connect_to_database()
if not conn:
return
cur = conn.cursor()

while True:
display_menu()
choice = input("Enter your choice: ")

if choice == "1":
17
log_exercise(cur)
elif choice == "2":
view_exercise_log(cur)
elif choice == "3":
calculate_total_calories_burned(cur)
elif choice == "4":
calculate_total_duration(cur)
elif choice == "5":
view_exercise_statistics(cur)
elif choice == "6":
delete_exercise_log(cur)
elif choice == "7":
search_exercise_log(cur)
elif choice == "8":
sort_exercise_log(cur)
elif choice == "9":
update_exercise_log(cur)
elif choice == "10":
calculate_total_steps(cur)
elif choice == "11":
print("Exiting Fitness Tracker. Goodbye!")
break
else:
print("Invalid choice. Please try again.\n")

conn.commit()

cur.close()
conn.close()

# Ensure the script runs only when executed directly


if __name__ == "__main__":
main()

18
Python Output:

19
20
21
22
23
24
25
Purpose of Testing

Testing is a crucial phase in software development aimed at ensuring that the


application performs as expected. The primary objectives of testing are to
detect and fix bugs, validate functionalities, and enhance the system’s
reliability and user experience.

Types of Testing:

The testing process for the Fitness Tracker project involves:

White Box Testing: Focuses on testing the internal code and logic of the
application.
Black Box Testing: Concentrates on verifying the application's functionality
without examining its internal structure.

White Box Testing:

White Box Testing involves analyzing the internal workings of the system. It
is also called structural or glass-box testing.
Testing Scenarios:
Step Count Functionality

Objective: Ensure the algorithm correctly increments the step count.


Test Case: Simulate user steps and validate calculations in the code.

Expected Result: The step count matches the number of steps entered
manually.

Calorie Calculation Logic

Objective: Verify the accuracy of the calorie estimation formula.


Test Case: Input varying activity levels and validate the formula's output.

Expected Result: Accurate calorie values based on activity input.

26
Black Box Testing
Black Box Testing focuses on the functional aspects of the application.
Testers evaluate the system by providing inputs and observing outputs
without accessing the code.

1. User Interface Functionality


o Objective: Ensure all GUI elements operate correctly.
o Test Case: Click buttons, navigate menus, and use input fields.
o Expected Result: The interface responds appropriately to user
actions.

2. Input Validation
o Objective: Verify how the system handles valid and invalid
inputs.
o Test Case: Input non-numeric values into the step tracker.
o Expected Result: The system rejects invalid inputs and prompts
for valid data.

3. Data Visualization
o Objective: Test graphical representations of fitness data.
o Test Case: Input activity data and generate reports.
o Expected Result: Graphs and charts are displayed accurately.

Performance Testing:

 Objective: Evaluate system response time under various conditions.


 Test Case: Simulate a large number of user records in the database.

 Expected Result: The application performs without significant delays.

Results:

The application passed all functional tests, demonstrating its reliability and
usability.

27
Conclusion:
An expense tracker is a powerful tool for managing personal finances and
fostering financial responsibility. By recording daily expenses and
categorizing them, users can gain valuable insights into their spending habits,
identify areas for savings, and make more informed financial decisions.
Whether the goal is to create a budget, save for a specific purpose, or simply
avoid overspending, an expense tracker provides the clarity and structure
needed to stay on track. Ultimately, it empowers users to take control of their
financial future and achieve greater financial stability.

SOFTWARE & HARDWAREREQUIREMENTS

OPERATING SYSTEM:
Windows 10 Pro

PROCESSOR:
Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz 2.90 GHz

MOTHERBOARD:
Manufacturer:Gigabyte technologies Version: x.x

RAM: HARD DISK:


8.00 GB SSD-240GB

SOFTWARE REQUIREMENTS:
28
1.Windows 2.My SQL 3.Python

RELATIONAL MODEL
It's based on the concept of relation. Relation is the table that consists of
rows and columns. The rows of the table are called tuple’s and the columns of
the table are called attributes. The number of rows in the table is called
cardinality. Number of columns in the table is called degree.

HIERARCHICAL MODEL

In this type of model, we have multiple records for each record. A particular
record has one parent record. No child record can exist without a parent

record. In this, the records are organized in trees.

NETWORK MODEL:
In this, the data is represented by a collection of records and relationships are
represented by (ink or association).

CHARACTERISTICS OF DBMS:
 It reduces the redundancy
 Reduction of data in inconsistency
 Data sharing
 Data standardization

DIFFERENT TYPES OF FILES:

BASED ON ACCESS:
29
 Sequential file
 Serial file
 Random (direct access) file

BASED ON STORAGE:

 Text file
 Binary file

INSTALLATION PROCEDURE

1. Install python and mysql from the web.


2. Open mysql and create the database bank.
3. Then run the table.py file.
4. Next run the usertable.py file.
5. Then the transactiontable.py file.
6. Open the main table file.
7. Then register your account.

USE OF TECHNOLOGY

Python is a high-level, general-purpose programming language.


Its design philosophy emphasizes code readability with the use of
significant indentation.
Python is dynamically typed and garbage-collected. It supports
multiple programming paradigms, including structured (particularly
procedural), object- oriented and functional programming.
It is often described as a batteries included language due to its
30
comprehensive standard library. Guido van Rossum began working on
Python in the late 1980s as a successor to the ABC programming
language and first released it in 1991 as Python 0.9.0.
Python 2.0 was released in 2000. Python 3.0, released in 2008, was
a major revision not completely backward- compatible with earlier
versions. Python 2.7.18, released in 2020, was the last release of Python
2.
Python consistently ranks as one of the most popular programming
languages, and has gained widespread use in the machine learning
community.

MySQL is an open-source relational database management system


(RDBMS). Its name is a combination of “MY”, the name of co-founder
Michael Widenius daughter My, and “SQL”, the acronym for Structured
Query Language.
A relational database organizes data into one or more data
tables in which data may be related to each other; these relations help
structure the data. SQL is a language that programmers use to create,
modify and extract data from the relational database, as well as control
user access to the database.
In addition to relational databases and SQL, an RDBMS like
MySQL works with an operating system to implement a relational
database in a computer’s storage system, manages users, allows for
network access and facilitates testing database integrity and creation of
backups.

MySQL is free and open-source software under the terms of the GNU
31
General Public License, and is also available under a variety of
proprietary licenses. MySQL was owned and sponsored by the Swedish
company MySQL AB, which was bought by Sun Micro-systems (now
Oracle Corporation).

In 2010, when Oracle acquired Sun, Widenius forked the open- source
MySQL project to create Maria DB.

THE NECESSITY OF INTERFACING PYTHON WITH


SQL DATABASE:

All databases are required to store the data, and manage the data. The way of
handling these sets of operations is called CRUD operations. Python is a user-
friendly language and it is able to get connected to any database easily via the
above ways.

Once proper installation is done, Python and that database can be connected.
Any CRUD operations can be handled easily.

 In Python, we will be receiving the inputs from various sources.


 Python will work on the inputs and produce the desired output upon
certain computations.
 The final output can be stored in the database if we interface with Python
and SQL databases.
 For interfacing Python and the database, we need to install it
differently. That differs with the operating system as well.

CONNECTING TO MYSQL FROM PYTHON:


32
Once the connector is installed you are ready to connect your python program
to mysql.
The following steps to follow while connecting your python program with
MySQL:

 Open Python
 Import the packages required (import mysql.connector)
 Open the connection to database
 Create a cursor instance
 Execute the query and store it in result set
 Extract data from result set
 Clean up the environment

FETCHING DATA FROM RESULT SET

To extract from cursor following functions are used:


 fetchall(): It will return all the records in the form of tuple.
 fetchone(): It will return one record from the result set i.e., the first time it
will return the first record, next time it will return the second record and so
on. If no more records it will return None.
 fetchmany(n): It will return n number of records. If there is no more record
it will return an empty tuple.
 rowcount: It will return the number of rows retrieved from the cursor so
far

Bibliography:

Preeti Arora
W3School
https://docs.python.org/3/tutorial/
33
34

You might also like