70 Python Experiment No. 14 Nakhwa Arman Anis

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Finolex Academy of Management and Technology, Ratnagiri

Department of Information Technology

Subject: Python Lab. (ITL404)

Class: SE IT / Semester – IV (Rev-2019 ‘C’) / Academic year: 2020-21

Name of Student: Kadam Rushikesh Dattatray

Roll No: 75 Date of performance (DOP) :

Assignment/Experiment No: 14 Date of checking (DOC) :

Title: Program to demonstrate Database operations in Python

Marks: Teacher’s Signature:

1. Aim: To understand database programming in Python.


2. Prerequisites:
1. Basics of programming disciplines.

3. Hardware Requirements:
1. PC with minimum 2GB RAM

4. Software Requirements:
1. Windows / Linux OS.
2. Python 3.6 or higher

5. Learning Objectives:
1. To understand database.
2. To understand how to install and start MySQL database server.
3. To know working with XAMPP GUI.
4. To understand how to perform CRUDE operations on MySQL database

6. Learning Objectives Applicable: LO 3


7. Program Outcomes Applicable: PO1, PO3, PO4, PSO1
8. Program Education Objectives Applicable: PEO 1, PEO5, PEO6
9. Theory:
A database is an organized collection of data, so that it can be easily accessed and managed. You
can organize data into tables, rows, columns, and index it to make it easier to find relevant
information. Database handlers create a database in such a way that only one set of software
program provides access of data to all the users. The main purpose of the database is to operate a
large amount of information by storing, retrieving, and managing data. There are many dynamic
websites on the World Wide Web nowadays which are handled through databases. For example,
a model that checks the availability of rooms in a hotel. It is an example of a dynamic website that
uses a database.

What is SQL?

 SQL stands for Structured Query Language


 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of
the International Organization for Standardization (ISO) in 1987

What Can SQL do?

 SQL can execute queries against a database


 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It
implements the Python Database API v2.0 and is built on top of the MySQL C API.

How do I Install MySQLdb?


Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the
following in your Python script and execute it −
#!/usr/bin/python
If it produces the following result, then it means MySQLdb module is not installed −

Traceback (most recent call last): File


"test.py", line 3, in <module>

import MySQLdb
ImportError: No module named MySQLdb

To install MySQLdb module, for Python command prompt, use the following command -
pip install MySQL-python

Database Connection
Before connecting to a MySQL database, make sure of the followings −
 You have created a database TESTDB.
 You have created a table EMPLOYEE in TESTDB.
 This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
 User ID "testuser" and password "test123" are set to access TESTDB.
 Python module MySQLdb is installed properly on your machine.
 You have gone through MySQL tutorial to understand MySQL Basics.

Example
Following is the example of connecting with MySQL database "TESTDB"
import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")
Creating Database Table
Once a database connection is established, we are ready to create tables or records into the
database tables using execute method of the created cursor.

Example
Let us create Database table EMPLOYEE −
import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement sql


= """CREATE TABLE EMPLOYEE (

FIRST_NAME CHAR(20) NOT NULL,


LAST_NAME CHAR(20),

AGE INT,

INSERT Operation
It is required when you want to create your records into a database table.

Example
The following example, executes SQL INSERT statement to create a record into EMPLOYEE
table –
#!/usr/bin/python import

MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database. sql =


"""INSERT INTO EMPLOYEE(FIRST_NAME,

LAST_NAME, AGE, SEX, INCOME)

VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""

try:

# Execute the SQL command


cursor.execute(sql)

# Commit your changes in the database


db.commit()

except:

Example
Following code segment is another form of execution where you can pass parameters directly –

user_id = "test123"
password = "password"

con.execute('insert into Login values("%s", "%s")' % \


(user_id, password))
READ Operation
READ Operation on any database means to fetch some useful information from the database.
Once our database connection is established, you are ready to make a query into this
database. You can use either fetchone() method to fetch single record or fetchall() method
to fetch multiple values from a database table.
 fetchone() − It fetches the next row of a query result set. A result set is an object that is
returned when a cursor object is used to query a table.
 fetchall() − It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result set.
 rowcount − This is a read-only attribute and returns the number of rows that were
affected by an execute() method.

Update Operation
UPDATE Operation on any database means to update one or more records, which are already
available in the database.

DELETE Operation
DELETE operation is required when you want to delete some records from your database

Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the following
four properties −
 Atomicity − Either a transaction completes or nothing happens at all.
 Consistency − A transaction must start in a consistent state and leave the system in a
consistent state.
 Isolation − Intermediate results of a transaction are not visible outside the current
transaction.
 Durability − Once a transaction was committed, the effects are persistent, even after a
system failure.
COMMIT Operation
Commit is the operation, which gives a green signal to database to finalize the changes, and after
this operation, no change can be reverted back.

ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back those
changes completely, then use rollback() method.

Disconnecting Database
To disconnect Database connection, use close() method.

10. Results:
1. To Create Database

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021
2. Insert Data in database

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021
3. Delete record from database

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021
4. Update record in database

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021
5. To display the data stored in database on the Python Shell

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021
6.

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021
11. Learning Outcomes Achieved:
1. Got knowledge about database.
2. Understood how to install and start MySQL database server.
3. Got to know about working with XAMPP GUI.
4. Understood how to perform CRUDE operations on MySQL database

12. Conclusion:
Hence, we understood database programming in Python.

13. Experiment/Assignment Evaluation

Experiment/Assignment Evaluation:

Sr. No. Parameters Marks Out of


obtained

1 Technical Understanding (Assessment may be done based on Q & A or any other relevant 6
method.) Teacher should mention the other method used -

2 Neatness/presentation 2

3 Punctuality 2

Date of performance (DOP) Total marks obtained 10

Date of checking (DOC) Signature of teacher

References:
[1] James Payne, “Beginning Python using Python 2.6 and Python 3.1”, Wrox Publications.
[2] Dr. R. Nageswara Rao, “Core Python Programming”, Dreamtech Press, Wiley Publications.
[3] Charles R. Severance “Python for Everybody: Exploring Data in Python 3”

Viva Questions
1. What do you mean by database?
2. Why to prefer a standard database over file based data storage?
3. Which Python package is required to facilitate MySQL database operations in Python.

FAMT/ IT / Semester – IV (Rev-2019 ‘C’) / Lab experiment / Academic Year: 2020-21 / First Half 2021

You might also like