Chapter 131415 and 16 Data Management
Chapter 131415 and 16 Data Management
com/
CLASS-XII
COMPUTER SCIENCE-PYTHON (083)
UNIT-III DATA MANAGEMENT-2
By: Vikash Kumar Yadav
PGT-Computer Science
K.V. No.-IV ONGC Vadodara
3.1 Django Introduction:
Django is a free and open source web application framework written in Python.
It is based on Model-View-Template (MVT) framework. Here Model means tables,
View means logic and Template means HTML files to display the contents interactive.
It is used for developing the web application.
Django provides the concept of ‘reusability’.
https://padhaaii.wordpress.com/ Page 1
Here Vehicle is the name of Project. A folder with the name Vehicle will be created in
D:\ WebApplications directory.
Vehicle
Vehicle manage.py
https://padhaaii.wordpress.com/ Page 2
3.3.2 Run the Django Server:
Now to start the Django server, Type following command in command prompt:
D:\WebApplications\Vehicle>python manage.py runserver
https://padhaaii.wordpress.com/ Page 3
3.3.3 Create an Application:
Now, open the command prompt. Go to the directory D:\WebApplications\Vehicle and
create the application under Vehicle Project. Here the application name is Car. To
create this application, type the following command :
After this, a folder will be created under Vehicle folder (Outer folder) and the structure
of directory will look like this:
Vehicle
__init__.py migrations
__init__.py
settings.py
admin.py
urls.py
apps.py
wsgi.py
models.py
tests.py
views.py
https://padhaaii.wordpress.com/ Page 4
3.3.4 Register the Application in Project:
Now register the created application Car under the project Vehicle. For this, we have
to open settings.py file under Vehicle folder.
In this web application we will perform the CRUD (Create, Read, Update, Delete )
operations.
We shall store the data of different types of cars and perform the CRUD operations
with the data stored in database.
To Store the data, we will use sqlite3 database system which is in-built in Django. So
no need to install it separately.
Open the file models.py under Car web application to create a model and its fields.
Models are considered as tables in MVT framework. An application may have multiple
models. Write the following code in models.py:
https://padhaaii.wordpress.com/ Page 5
Here, Meta class is simply an inner class. In Django, the use of Meta class is simply to
provide metadata to the ModelForm class.
Django provides the facility of forms. It means we need not create any HTML form for
table fields. Django denotes the table fields as a form. Now, create a file forms.py
under Car folder.
Now migrate the models in database. For this, we have to run the following command
in command prompt:
D:\WebApplications\Vehicle>python manage.py makemigrations
This command will create the model and make the changes if any.
Now run another command to migrate the created model. In command prompt window,
write the following command:
D:\WebApplications\Vehicle>python manage.py migrate
https://padhaaii.wordpress.com/ Page 6
Now the created model is stored in the file 0001_initial.py under the folder migration in Car
application.
A table named as ctable has been created in database. It has following fields:
(id, cbrand, cdom, cprice). id field is automatically created in Django, which has its
own system generated values.
Make the entry of created folder in settings.py file. The meaning of this step that we
are informing the project that there is an application with the name Car, whose all
.html pages are inside templates folder.
In our application, we will have index.html, edit.html and show.html files under
templates folder.
https://padhaaii.wordpress.com/ Page 7
HTML coding for index.html:
In this file we’ll create an HTML form to take the values from user.
(CREATE operation)
<html>
<head><title>Index Page</title></head>
<body>
<center><strong>
<h1>CAR DATA</h1>
</strong></center>
<center>
In above code, csrf_token is inbuilt feature of django application. csrf stands for Cross Site
Request Forgery. It provides easy-to-use protection against Cross Site Request Forgeries.
<html>
<head>
<title>Show Car Details</title>
</head>
<body>
<center><strong><u><h1>CAR DETAILS</h1></u></strong></center>
<center>
<table width=60% border=6">
<tr>
<th>Car Brand</th>
<th>Date of Manufacturing</th>
<th> Price</th>
https://padhaaii.wordpress.com/ Page 8
<th colspan="2">Action</th>
</tr>
https://padhaaii.wordpress.com/ Page 9
3.3.8 Write the logic in views.py:
Now, open views.py under the application Car.
views.py file will work as a controller. In this file we would write the logics in the form
of functions and call the views according to their actions. So, it is an important file.
https://padhaaii.wordpress.com/ Page 10
3.3.9 Write the logic in views.py
Open urls.py under Vehicle subfolder and refer the views. Write the following code
in urls.py file.
After execution of above command, the following address will appear on command
prompt:
http://127.0.0.1:8000/
Copy it and paste it into web browser. Press Enter. It will display the name of all urls.
Now write the address of the show page. Means, write the address given below:
http://127.0.0.1:8000/show
https://padhaaii.wordpress.com/ Page 11
OUTPUT:
https://padhaaii.wordpress.com/ Page 12
OUTPUT-3 Records in the table after addition
https://padhaaii.wordpress.com/ Page 13
3.4 CSV and Flat Files:
CSV (Comma Separated Values). A csv file is a type of plain text file that uses specific
structuring to arrange tabular data. csv is a common format for data interchange as it is
compact, simple and general. Each line of the file is one line of the table. csv files have
.csv as file extension.
As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
To work with csv files, we have to import the csv module in our program.
CODE:
import csv
with open('C:\\data.csv','rt') as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)
OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
CODE:
import csv
with open('C:\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"' )
#write new record in file
writer.writerow(['3', 'Shivani', 'Commerce', '448'])
writer.writerow(['4', 'Devansh', 'Arts', '404'])
https://padhaaii.wordpress.com/ Page 14
OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']
When we shall open the file in notepad (Flat file) then the contents of the file will look
like this:
Roll No.,Name of student,stream,Marks
1,Anil,Arts,426
2,Sujata,Science,412
3,Shivani,Commerce,448
4,Devansh,Arts,404
https://padhaaii.wordpress.com/ Page 15
Open urls.py, and write following code:
After successful execution of above, write the given address in web browser.
http://127.0.0.1:8000/csv
If the command successfully runs (without any error), then the MySQL connector is
successfully installed.
Now, open MySQL and check the current user, by typing the following command in
MySQL:
SELECT current_user( );
https://padhaaii.wordpress.com/ Page 16
Connect MySQL database with python. For this, open Python IDLE and write the
following code in python file.
CODE:
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root", passwd="computer")
print(demodb)
If you get the following output, then the connection made successfully.
OUTPUT:
After making successful connection between python and MySQL, now create a
database in MySQL through python. For that, write the following code in python:
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="computer")
democursor=demodb.cursor( )
democursor.execute("CREATE DATABASE EDUCATION")
https://padhaaii.wordpress.com/ Page 17
If you want to check the created database through python, write the following python
code to show the present databases in MySQL.
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="computer")
democursor=demodb.cursor()
democursor.execute("SHOW DATABASES")
for i in democursor:
print(i)
OUTPUT:
To verify the table created or not, write the following code in python:
import mysql.connector
https://padhaaii.wordpress.com/ Page 18
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor = demodb.cursor( )
democursor.execute ("show tables")
for i in democursor:
print(i)
OUTPUT:
OUTPUT:
https://padhaaii.wordpress.com/ Page 19
3.10 Update the record:
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
(i) Data Definition Language (DDL): It consist the commands to create objects such as
tables, views, indexes etc. in the database.
https://padhaaii.wordpress.com/ Page 20
(ii) Data Manipulation Language (DML): It is used for queries. It allows you to perform
data manipulation e.g. retrieval, insertion, deletion, modification of data stored in
database.
(iii) Transaction Control Language (TCL): This language allows you to manage and
control the transaction.
(iv) Data Control Language (DCL): This language is used to control data and access
to the databases. It is used for protecting the data from unauthorized access.
https://padhaaii.wordpress.com/ Page 21
Example: USE Bank;
DROPPING DATABASES: To remove the entire database we use the DROP DATABASE
statement.
Syntax: DROP DATABASE <database-name>;
Example: DROP DATABASE Bank;
Fig. : EMPLOYEE
The into clause specifies the target table and the value clause specifies the data to be
added to the new row of the table.
While inserting data into tables, following points should be taken care of:
Character data should be enclosed within single quotes.
NULL values are given as NULL, without any quotes.
If no data is available for all the columns then the column list must be included,
following the table name. Example: INSERT INTO EMPLOYEE(Ecode, Ename,
salary) VALUES(1001, ‘Amit’, 20000.00);
Table: EMPLOYEE
DROPPING A TABLE:
To remove the entire structure of the table completely, we use the DROP TABLE
command.
Syntax:
https://padhaaii.wordpress.com/ Page 23
DROP TABLE <table-name>;
Example:
DROP TABLE EMPLOYEE;
(i) SELECT Command:- A SELECT command retrieves information from the database.
(ii) INSERT Command:- This command is used to insert the data in table.
NOTE:- We have already discussed about this command.
(iii) DELETE Command:- It means delete the information from the table. This command is
used to remove the rows from the table.
Specific rows are deleted when you specify the WHERE clause.
All rows in the table are deleted if you omit the WHERE clause.
(i) SELECT:-
A SELECT command is used to retrieve information from a table.
If you want to select the all columns from a table, then we use the
asterisk(*) in SELECT clause.
Example: - SELECT * FROM EMPLOYEE;
To display specific columns of the table by specifying the column names,
separated by commas.
Example: - SELECT Ecode, Ename, salary
FROM EMPLOYEE;
(ii) FROM:-
A FROM clause, specifies the table name that contains the columns.
(iii) WHERE:-
A WHERE clause, specifies the condition.
https://padhaaii.wordpress.com/ Page 25
SOME IMPORTANAT POINTS:-
SQL statements are not case sensitive.
To end the SQL command, we write the semicolon(;) at the end of a line followed by
<ENTER>.
Selecting All Columns:- To select all the columns, we use asterisk (*) in SELECT
statement.
Example:- SELECT *
FROM EMPLOYEE;
Selecting Specific Columns:- To display the specific columns of the table, write
columns name, separated by commas.
Example:- SELECT Ecode, Ename, salary
FROM EMPLOYEE;
ALL keyword:-
SQL allows us to use the keyword ALL to specify explicitly that duplicates are not
removed.
Example: SELECT ALL Dept
FROM EMPLOYEE;
Arithmetic Operations:-
The SELECT clause may also contain arithmetic expressions involving the operators +, - ,
* and / operating on constants or attributes.
Example:- Find the new salary of every employee increased by 25%.
SELECT Ename,salary,salary*0.25
FROM EMPLOYEE;
COLUMN ALIAS:- You can change a column heading by using a column alias.
Example:- SELECT Ename as Name
https://padhaaii.wordpress.com/ Page 26
FROM EMPLOYEE;
Examples of Queries:-
1. List the name and department of those employees where department is production.
Solution:- SELECT Ename, Dept
FROM EMPLOYEE
WHERE Dept=’production’;
2. Find the name and salary of those employees whose salary is more than 20000.
Solution:- SELECT Ename, salary
FROM EMPLOYEE
WHERE salary > 20000;
5. Display the name and department of those employees who work in surat and salary is
greater than 25000.
Solution:- SELECT Ename, Dept
FROM EMPLOYEE
WHERE city=’surat’ and salary > 25000;
https://padhaaii.wordpress.com/ Page 27
8. List the name of employees who are not males.
Solution:- SELECT Ename, Sex
FROM EMPLOYEE
WHERE sex!=’M’;
(i) BETWEEN :-
Example:- Find the name and salary of those employees whose salary is between
35000 and 40000.
Solution:- SELECT Ename, salary
FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
Or we can write this query in another way:
SELECT Ename, salary
FROM EMPLOYEE
WHERE salary>35000 and salary<40000;
(ii) IN :-
Example:- Find the name of those employees who live in guwahati, surat or jaipur
city.
Solution:- SELECT Ename, city
FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
(iii) LIKE :-
% :- It represents any sequence of zero or more characters.
_ :- Represents any single character.
Example:- Display the name of those employees whose name starts with ‘M’.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE ‘M%’;
Example:-Display the name of those employees whose department name ends with ‘a’.
https://padhaaii.wordpress.com/ Page 28
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Dept LIKE ‘%a’;
Example:- List the name of employees whose name having ‘e’ as the second character.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE ‘_e%’;
(iv) IS NULL :-
Aggregate functions are functions that take a collection of values as input and return a
single value. SQL offers five types of aggregate functions:-
https://padhaaii.wordpress.com/ Page 29
(i) Avg( ) :- To findout the average
(ii) Min( ) :- Minimum value
(iii) Max( ) :-Maximum value
(iv) Sum( ) :-To calculate the total
(v) Count( ) :- For counting
NOTE: - The input to sum ( ) and avg( ) must be a collection of numbers, but the other
functions can operate on non numeric data types e.g.string.
In some circumstance, we would like to apply the aggregate function not only to a single
set of tuples, but also to a group of sets of tuples. We specify this wish in SQL using the
group by clause.
The attributes given in the group by clause are used to form groups.
Dept Avg(salary)
Production 38000.00
Marketing 35410.00
RND 40016.66
Q.5 Find the total salary of those employees who work in Guwahati city.
Solution:- SELECT sum(salary)
https://padhaaii.wordpress.com/ Page 30
FROM EMPLOYEE
WHERE city=’Guwahati’;
Q.9 Show the name of each department and minimum salary where minimum salary
in the department is less than 8000.
Solution: SELECT Dept, min(salary)
FROM EMPLOYEE
group by Dept
HAVING min(salary) < 8000;
Note: HAVING clause is often used with GROUP BY clause to apply filter condition for a
group of rows.
Q.10 Find maximum salary of each department and display the name of that
department which has maximum salary more than 39000.
Solution: SELECT Dept, max(salary)
FROM EMPLOYEE
group by Dept
HAVING max(salary)>39000;
https://padhaaii.wordpress.com/ Page 31