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

DBMS

Uploaded by

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

DBMS

Uploaded by

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

UNIT – 3 DATABASE MANAGEMENT

MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database, information is stored in Tables. A
single MySQL database can contain many tables at once and store thousands of individual
records.

SQL (Structured Query Language)


SQL is a language that enables you to create and operate on relational databases, which are sets of
related information stored in tables.

ADVANTAGES OF USING DBMS

➢ Reducing data redundancy – This ensures a consistent database and efficient use of
storage space.
➢ Aiding multiple views of the data: Database management system enables different users
to have a view of the data from their own perspective
➢ Implementation of data integrity The term data integrity refers to the accuracy and
consistency of data. When creating databases, attention needs to be given to data integrity
and how to maintain it.
➢ Data sharing and security – DBMS limits the accessibility of the data to the authorized
users only. This makes data sharing safer. Moreover shared data makes it possible to fulfill
data requirements with minimal modifications.
➢ Centralized data ensures a more effective backup and recovery process than the
conventional file processing systems.
➢ Program & Data independence: Programs and the data are not mutually dependent. If a
programmer wants to change the structure of the database then he/she can do so without
affecting the application programs that are using the database.
➢ Data Abstraction: It ensures that the users get an abstract view of the data without showing
implementation details and the physical storage of thedata.

RELATIONAL MODEL TERMINOLOGY

1. Relation: A table storing logically related data is called a Relation.

160
2. Tuple: A row of a relation is generally referred to as a tuple.

3. Attribute: A column of a relation is generally referred to as an attribute.

4. Degree: This refers to the number of attributes in a relation.

5. Cardinality: This refers to the number of tuples in a relation.

6. Primary Key: This refers to a set of one or more attributes that can uniquely identify tuples
within the relation.
7. Candidate Key : All attribute combinations inside a relation that can serve as primary
key are candidate keys as these are candidates for primary key position.
8. Alternate Key: A candidate key that is not primary key, is called an alternate key.

9. Foreign Key : A non-key attribute, whose values are derived from the primary key of
some other table, is known as foreign key in its current table.
REFERENTIAL INTEGRITY
A referential integrity is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t accidentally delete or
change related data. This integrity is ensured by foreign key.
CLASSIFICATION OF SQL STATEMENTS
SQL commands can be mainly divided into following categories:

DATA TYPES
Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into three categories:
➢ Numeric
➢ Date and time
➢ String types

Numeric Datatype
1. int– used for number without decimal.

161
2. decimal(m,d) – used for floating/real numbers. m denotes the total length of number
and d is number of decimal digits.
Date and Time Datatype
1. date–used to store date in YYYY-MM-DD format.
2. time–used to store time in HH:MM:SS format.
String Datatype
1. char(m)–used to store a fixed length string, m denotes max. number of characters.
2. varchar(m)–used to store a variable length string, m denotes max. no. of characters.
DATABASE COMMANDS
1. VIEW EXISTING DATABASE
To view existing database names, the command is: SHOW DATABASES;

2. CREATING DATABASE IN MYSQL


For creating the database in MySQL, we write the following command:
CREATE DATABASE <databasename>;
e.g.In order to create a database Student, command is:
CREATE DATABASE Student;
3. ACCESSING A DATABASE
For accessing already existing database,we write:
USE<databasename>;
e.g.to access a database named Student, we write command as:
USE Student;
4. DELETING DATABASE
For deleting any existing database,the command is:
DROP DATABASE <databasename>;
e.g.to delete a database, say student, we write command as:
DROP DATABASE Student;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database, command is:
SHOW TABLES;
CREATING TABLES IN MYSQL
Syntax of CREATE TABLE command is:
CREATE TABLE <table-name>(<colname> datatype,<colname> datatype,…);
E.g. Inorder to create table EMPLOYEE given below:
ECODE ENAME GENDER GRADE GROSS
Create table employee (ecode integer, ename varchar(20),gender char(1),grade char(2),gross
integer);
Inserting Data into Table:
Syntax:
Insert into <tablename> values(<v1>,<v2>,…);
Or
Insert into <tablename>(<column list> )values(<values list>);

162
Eg: insert into employee values(1001,‘Ravi’,‘M’,‘E4’,50000);
Or
Insert into employee(ecode,ename)values(1002,’Meena’);
The left out columns will be filled with null values.

Select Command:

It helps to display the records as per our requirement.

Different forms of select command:


1. Select * from employee;
It displays all rows and columns from the table.

2.Select ecode, ename from employee;


It displays selected columns from the table.

3.For displaying particular rows.


Syntax: select * from <tablename> where <cond>;
Eg. Select * from employee where gender=’M’;

4. ELIMINATING REDUNDANT DATA


The distinct keyword is used to eliminate duplicate records from the table.

Eg. Select distinct (gender) from employee;


DISTINCT(GENDER)
M
F

5. USING COLUMN ALIASES


The columns that we select in a query can be given a different name, i.e.column alias name for
output purpose.
Syntax: SELECT <columnname>AS column alias ,<columnname>AS column alias
…..FROM<tablename>;
Eg.select ecode as “EMP_Code” from employee;
CONDITION BASED ON A RANGE
The BETWEEN operator defines a range of values that the column values must fall into make the
condition true. The range include both lower value and upper value.

e.g.To display ECODE,ENAME and GRADE of those employees whose salary is between 40000
and 50000,command is:
SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000;

163
NOTE: For displaying records not in the specified range, we have to use not between operator.
CONDITION BASED ON A LIST
The in operator is used to display records based on a list of values.
Eg. To display details of employees who have scored A,B and C grades.
Select * from employee where grade in(‘A’,’B’,’C’);
Note: For displaying records that do not match in the list, we have to use not in operator.

CONDITION BASED ON PATTERN MATCHES

LIKE operator is used for pattern matching in SQL. Patterns are described using two special
wildcard characters: % and _ (underscore)
1. percent(%)– The % character matches any substring.
2. underscore(_)– The _ character matches any single character.
e.g.To display names of employee whose name starts with R in EMPLOYEE table, the command is:
select ename from employee where ename like “R%”;

e.g. To display details of employee whose second character in name is:


select * from employee where ename like ‘_e%’;

SEARCHING FOR NULL


The NULL value in a column can be searched for in a table using IS NULL in the WHERE
clause. E.g. to list employee details whose salary contain NULL, we use the command:
Select * from employee where gross is null;
Note: For listing employees who earn salary, then it is:
Select * from employee where gross is not null;
Relational Operators
• To compare two values, a relational operator is used. The result of the comparison is true or false.
Relational Operators recognized by SQL: =, >, <, <=, >=, <> (not equal or !=)

Eg. Select * from employee where ecode <> 1001;


Above query will not display those employee details whose ecode column value is 1001.

Logical Operators- (OR, AND, NOT)

1) To list the employee details having grades E2 or E3.


Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’);

2) To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
164
Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000;

3) To list all the employees’ details whose grades are other than ‘G1’.
Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);

Sorting Results- ORDER BY clause

Results of SQL query can be sorted in a specific order using ORDER BY clause.
The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be
done either in ascending or descending order.

Eg. Select * from emp order by ename;


Above query arranges the records in alphabetical order of ename value. By default order by clause
arranges in ascending order.

TO DISPLAY RECORDS IN DESCENDING ORDER

❖ Select * from employee order by ename desc;


Above query gives output in descending order of ename.
❖ Select * from employee ORDER BY grade DESC, ename ASC;
Above query displays records first in the descending order of grade and within the same
grade, employees are displayed in the ascending order of Ename.

SQL AGGREGATE FUNCTIONS:


All the aggregate functions ignore null values except count(*).

Avg – to compute average value


Min – to find minimum value
Max – to find maximum value
Sum – to find total value
Count – to count non-null values in a column
Count( *) – to count total number of rows in a table including null values.

Examples:
Select avg(gross) from employee;
Select min(gross) from employee where deptno= 10;
Select count(*) from emp where gross> 10000;
Select count (DISTINCT gender) from employee;

GROUP BY Clause

GROUP BY clause is used in SELECT statements to display the table contents based on similar
values in a column into groups.

165
Eg: To calculate the number of employees in each grade, the query is:
SELECT grade, count(*) from employee group by grade;

Placing conditions on Groups HAVING Clause

❖ The HAVING clause places conditions on groups in contrast to WHERE clause that places
conditions on individual rows.
❖ WHERE conditions cannot include aggregate functions but HAVING conditions can do so.

Eg: SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’ ;

DELETE Command

This command removes rows from a table.


Syntax: DELETE FROM <tablename> [WHERE <cond>];

Eg: To remove all the contents of items table, the query is:
DELETE from items;
Eg: To remove the tuples from employee that have gross less than 20000 is :
DELETE from employee WHERE gross<20000;

UPDATE Command

Update Command allows to change some or all the values in an existing rows. Update command
specifies the rows to be changed using the WHERE clause and the new data using the SET
keyword.
Eg. UPDATE employee SET gross= 25000;
The above query sets the gross of all records as 25000.

UPDATE employee SET gross=40000, grade=’A’ WHERE ecode=1001;


The above query changes the gross and grade values for the record with ecode 1001.

ALTER TABLE

ALTER TABLE command is used to change the structure of the existing table. It can be used to add
or drop new columns or modify the existing columns of table.
Eg. 1. Alter table Employee Add comm int;
2. ALTER TABLE Emp MODIFY (ename varchar(60));
3. Alter table emp drop comm;

DROP TABLE:

DROP TABLE command allows to remove a table from database. Once the DROP command is
issued, the table will no longer be available in the database.

166
Eg. DROP TABLE employee;

INTEGRITY CONSTRAINTS
A constraint is a condition or check applicable on a field or set of fields.
Common types of constraints include:

S.No. Constraints Description


1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none is
specified
3 UNIQUE Ensures that all values in a column are different
4 PRIMARY KEY Used to uniquely identify a row in the table
5 FOREIGN KEY Used to ensure referential integrity of the data

ADDING CONSTRAINT TO A TABLE

ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:

Eg: alter table employee add primary key(ecode);


REMOVING CONSTRAINTS FROM A TABLE
Eg: alter table employee drop primary key;

Setting primary and foreign key constraint:

Eg: CREATE TABLE STUDENT(ROLL_NO integer PRIMARY KEY ,NAME


VARCHAR(30),CLASSVARCHAR(3));

CREATE TABLE SCORE(ROLL_NO integer ,MARKS integer, FOREIGN KEY(ROLL_NO)


REFERENCES STUDENT(ROLL_NO));

SQL JOINS

SQL Joins are essential to display data from more than one table. SQL JOIN clause is used to
combine rows from two or more tables, based on a common field between them. SQL provides
various types of joins:
1. Cartesian Product or Cross Join
2. Equi-Join
3. Natural Join.

Cartesian Product (Cross Join)


Cartesian product of two tables is obtained by pairing up each row of one table with each row of
the other table.
167
❖ The number of columns in the Cartesian product is the sum of the number of columns in
both the tables.
❖ The number of rows in the Cartesian product is the product of rows of the tables.
Example:

Equi-Join
A join which is obtained by putting a condition of equality on cross join is called an 'equi join'.
We can extract meaningful information from the Cartesian product by placing some conditions in the
statement.
The join in which columns are compared for equality is called equi-join.
In this type of join we put * in the select list therefore the common column will appear twice in the
output.
Example: Consider the 2 tables emp and dept.

On performing equi-join, the result is as follows:

168
Note: We see that deptno column appears twice in output.

Natural Join

• The join in which only one of the identical columns exists is called natural join.
• It is similar to equi-join except that duplicate columns are eliminated in natural join that would
otherwise appear in equi-join.
Example:

Note: We see that deptno column appears only once in output.

Worksheet – L3

Q1. What does the abbreviation DBMS stand for?

(a) Data Borrowing and Movement Software.


(b) Database Management System.
(c) DigitalBase Mapping System.
(d) Database Manipulation Software.

Q2. Which is not an advantage of DBMS?

(a) Database Systems reduce data redundancy


(b) Database Systems control data inconsistency
(c) Database Systems restrict sharing of data
(d) Database Systems ensure data security.

Q3. In ..............,the data is organized into tables i.e. rows &columns.


169
(a) Relational Model
(b) Network Model
(c) Hierarchical Model
(d) ObjectOriented Model

Q4. The essential features of Object Oriented Data Model are;

(a) Object identity


(b) Encapsulation
(c) DataAbstraction
(d) All of the above

Q5. Which statement is false in context to the term Relation?

(a) Relation is a table storing logically related data.


(b) Data must be atomic in cell
(c) All rows of relation are distinct.
(d) Ordering of rows & columns is relevant.

Q6. A row of relation generally referred to as ............. and column of a relation is


…………

(a) Domain & Attribute


(b) Attribute & Domain
(c) Tuple & Attribute
(d) Attribute & Tuple
Q7. A relation has 45 tuples & 5 attributes, what will be the Degree & Cardinality
of that relation?
(a) Degree5,Cardinality45
(b) Degree45,Cardinality5
(c) Degree50,Cardinality45
(d) Degree50,Cardinality2250

Q8. Is the attribute or group of attributes that uniquely identify


occurrence of each entity.
(a) Foreign key
(b) Super Key
(c) Primary Key
(d) All of these

Q9. A Candidate key that is not a primary key, is called ……………

170
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key

Q10.A non-key attribute, whose values are derived from primary key of some other
table.
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key

Q11. MySQL database system consists of-


(a) MySQLServerInstance
(b) MySQLDatabase
(c) MySQL Query Optimizer
(d) (a)&(b)both

Q12. Which commands are used to define or redefine schema objects?


(a) DDL
(b) DML
(c) TCL
(d) (a)&(b)both

Q13. Data definition includes:


(a) Creating of database
(b) Undoing changes to the database.
(c) Modification of data stored in the database.
(d) All of the above

Q14. Which is not a TCL command?


(a) Commit
(b) Rollback
(c) Exit
(d) Savepoint

Q15. Which is not a function of DML?


(a) Retrieval of data stored in the database
(b) Insertion of data into the database
(c) Deletion of data from the database
(d) Making changes permanent to the database.

Q16. Which is not a numeric type?


171
(a) Int
(b) Float
(c) Blob
(d) Double

Q17. The default date format in MySQL is:


(a) DD/MM/YYYY
(b) YYYY/MM/DD
(c) MM-DD-YYYY
(d) YYYY-MM-DD

Q18. Which is not a way to represent comment in MySQL?


(a)/* ------------- */
(b) --
(c) #
(d) //

Q19. The command is used to access database in MySQL is-


(a) Open <databasename>;
(b) USE <databasename>;
(c) Access <databasename>;
(d) (a)&(b) both

20. Which is a valid CREATE TABLE statement?


(a) Create table emp add(id integer(3));
(b) Create table emp(id integers(3));
(c) Create table emp modified(id integer(3));
(d) Create table emp(id integer(3));

Q21. How can you insert a new row into the “STORE” table.
(a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE;
(b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE;
(c) INSERT INTO(1,‟RAMSINGH‟)STORE;
(d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟);

Q22. Select statement has four clauses 1.Where 2.Having 3.Group By


4.Orderby

The correct order of all clauses in a select is:-


(a)1,2,3&4
(b)1,3,2&4
(c)1,4,3&2
(d)1,3,4&2
172
Q23. Conditionally retrieval of rows from a table with SELECT, which clause is
used?
(a) Where
(b) Having
(c) Group By
(d) Order by

Q24. The .................. key word eliminates duplicate rows from the result of a
SELECT statement.
(a) All
(b) Unique
(c) Distinct
(d) IN

Q25. Which operator defines a range of values that the column values must fall in?
(a) In
(b) Like
(c) Between
(d) Is
Q26. To specify a list of values ............... Operator is used.
(a) In
(b) Like
(c) Between
(d) Is

Q27. We use .................. operator with select for condition based on pattern matching.
(a) In
(b) Like
(c) Between
(d) Is

Q28. Which SQL statement will not generate any error message?
(a) SELECT*FROM EMP WHERE EMPNO LIKE(1,2,3,4);
(b) SELECT*FROM EMP WHERE SAL BETWEEN 3000 TO 15000;
(c) SELECT*FROM EMP WHERE COMM IS NOT NULL;
(d) All of the above

Q29.To display the detail of employee having ‘e’ in their name in descending order of
salary. The correct SQL statement is:
(a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL;
(b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE
173
“%e%”;
(c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC
SAL;
(d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL
DESC;

Q30. Which statement is valid?


(a) ALTER TABLE EMPLOYEE MODIFY(last_name CHAR2(2000));
(b) ALTER TABLE EMPLOYEE CHANGE(last_name CHAR2(2000));
(c) ALTERTABLE EMPLOYEE CHANGE(last_name VARCHAR2(2000));
(d) ALTER TABLE EMPLOYEE MODIFY(last_name VARCHAR2(2000));

174
Answers
Q.No. Answers
1 B
2 C
3 A
4 d
5 d
6 c
7 a
8 c
9 a
10 b
11 d
12 a
13 a
14 c
15 d
16 c
17 d
18 d
19 b
20 d
21 d
22 b
23 a
24 c
25 c
26 a
27 b
28 c
29 d
30 d

175
WORK SHEET -2

Q1. Which is true in respect of Select Statement?

(a) By Select we can retrieve all the rows from table.


(b) By Where clause with select we can retrieve selected rows from table.
(c) We can retrieve unique rows from table with the use of Distinct keyword.
(d) All of the above.

Q2. The clause which is used to group rows based on distinct values that exist
for specified column.

(a) Group by clause


(b) Having clause
(c) Order by Clause
(d) Where Clause

Q3. For conditionally retrieval of row from groups which clause is used?

(a) Where clause


(b) Having Clause
(c) Order By Clause
(d) (a)&(b)both

Q4. Group functions are also known as.

(a) Aggregate functions


(b) Multiple row functions
(c) Single row functions
(d) (a)&(b)both

Q5.Which option cause a group function to consider only distinct values.

(a) All
(b) Distinct
(c) Unique
(d) Diverse

Q6. Which option cause a group functions to consider all values including
all duplicated.

(a) All
(b) Distinct
(c) Unique
176
(d) Diverse

Q7. Which is not a group function?

(a) AVG
(b) COUNT
(c) MAX
(d) MOD

Consider the relations/tables EMP and DEPT and give the correct answer of following
queries.
Relation: EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10
Relation: DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Q8. SELECT AVG(SAL) FROM EMP WHERE JOB=‘CLERK’;

(a)1037.5
(b)2073.21
(c)1040
(d)2074

Q9. SELECT COUNT(*) FROM EMP WHERE DEPTNO=10;

(a) 14
(b) 3
(c) 4
(d) 5

177
Q10. SELECT COUNT(DISTINCT JOB) FROMEMP;

(a) 14
(b) 5
(c) 4
(d) 6

Q11. SELECT COUNT(ALL JOB)FROM EMP;

(a) 14
(b) 5
(c) 4
(d) 6

Q12. SELECT MAX(SAL) FROM EMP WHERE JOB=‘MANAGER’;

(a)2975
(b)5000
(c)3000
(d)2850

Q13. SELECT MIN(HIREDATE) FROM EMP;

(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None

Q14. SELECT MAX(HIREDATE) FROM EMP;

(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None

Q15. SELECT SUM(COMM) FROM EMP;

(a) Null
(b) 0
(c)2200
(d)1400

Q16.Which statement is used to display the total no. of employees in each


department?
(a) SELECT COUNT(*) FROM EMP WHERE DEPTNO;
178
(b) SELECTCOUNT(*)FROMEMPGROUPBYDEPTNO;
(c) SELECTCOUNT(DEPTNO)FROMEMPGROUPBYDEPTNO;
(d) (b)&(c)both

Q17. To display the jobs where the number of employees is less than 3.
(a) SELECT JOB,COUNT(*)FROM EMP WHERE COUNT(*)<3;
(b) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*)<3
GROUP BY JOB;
(c) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB WHERE
COUNT(*)<3;
(d) SELECT JOB,COUNT(*)FROM EMP GROUP BY JOB HAVING COUNT(*)
<3;

Q18.Which join is used for display all possible concatenations are formed of all
rows of two or more tables.

(a) Unrestricted join


(b) Cartesian Join
(c) Equi Join
(d) (a)&(b) both

Q19. How many rows are returned when we execute ‘SELECT*FROM EMP,DEPT’;

(a) 14
(b) 4
(c) 18
(d) 56

Q20.To display the name of employee & department name the MySQL statement
used:
(a) SELECT ENAME, DNAME FROM EMP,DEPT;
(b) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE DEPTNO=DEPTNO;
(c) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
(d) None of the above

Q21.The join where columns are compared for equality is called………………

(a) Equi Join


(b) Natural Join
(c) Cross Join
(d) Right Join

179
Q22. The join in which only one identical column exists is called………

(a) Equi Join


(b) Natural Join
(c) Cross Join
(d) Right Join

Q23. Which statement represent Cartesian join?

(a) SELECT*FROM EMP,DEPT;


(b) SELECT*FROM EMP JOIN DEPT;
(c) SELECT*FROM EMP CROSS JOIN DEPT;
(d) All of the above

Q24. Using sub-clause with JOIN causes a ................join where as on sub-clause


with JOIN produces .......... join.

(a) Natural & Equi


(b) Equi & Natural
(c) Cross & Equi
(d) Natural & Cross.

Q25. Scalar functions are also known as:

(a) Single row function


(b) Multiple row function
(c) Group functions
(d) None

180
Answers

Q.No. Answers
1 A
2 C
3 C
4 A
5 C
6 C
7 D
8 D
9 B
10 C
11 B
12 B
13 D
14 A
15 B
16 D
17 B
18 A
19 D
20 A
21 B
22 B
23 A
24 A
25 a
INTERFACE PYTHON WITH MYSQL

Basically the process of transfer data between python programs and MySQL database is known as Python
Database Connectivity.
There few steps you have to follow to perform Python Database Connectivity. These steps are as follow:
1. Import the required packages
2. Establish a connection
3. Execute SQL command
4. Process as per the requirements

Import the required packages

To perform the Python MySQL Database Connectivity you need to install mysql-connector-python package
using pip command.
pip install mysql connector python

After installation just write the import statement to import the package in python code.
import mysql.connector as msql

importing package mysql connector in python


Here I have instantiated msql to mysql.connector which can be work as an alias name for the connector.

Establish a connection

To establish a connection you need to create a connection object in Python. Take a variable as a connection
object and use connect() function with MySQL database specification like host name, username,
passoword or passwd and database itself. For example cn. Observe the code:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='root',database='Studentdb')

Please ensure that you have provided appropriate username, password and database name available in your
MySQL interface.

After doing this, check for the errors if any. If your program runs without errors that means connection is
established. Although you can use is_connected() function to check whether the connection is established
or not! Observe this code:

import mysql.connector as msql

182 | P a g e
cn=msql.connect(host='localhost',user='root',passwd='root',database='Student')
if cn.is_connected():
print("Connection Established")
else:
print("Connection Errors! Kindly check!!!")

Execute SQL command and fetch rows

The next step after the successful connection is to write SQL command and fetch rows. The SQL
commands are used to perform DML operations and fetch rows read data from table. So we will see them in
detail later.
You have to create a cursor object for executing SQL command and fetch rows. Cursor object is a special
kind of structure that processes the data row by row in database. You can create cursor object in the
following manner.

cur=cn.cursor()

Performing DML operations (insert, update and delete)

To perform the DML operations like insert, update or delete follow these steps:
1. Create a cursor object
2. Write command as parameters for execute() function
3. Use commit() function to save the changes and reflect the data in the table.

insert command

Observe the following code:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("insert into students values(1111,'Asmita',78.50,'B1'))
cn.commit()

update command

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("update students set marks=80.5 where rollno=1111")
cn.commit()

delete command

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
183 | P a g e
cur.execute("delete from students where rollno=1111")
cn.commit()

Select Command

As you know the select command is used retrieve records from the database. The result is available in the
resultset or dataset. You can store the select the command in cursor object in python. Then for resultset you
can use the fetch…() function. These are:
1. fetchall(): It will retrieve all data from a database table in form of record or tuple or a row.
2. fetchone(): It will retrieve one record from the resultset as a tuple or a list. It returns the records in a
specific order like first record, the next time next record and so on. If records are not available then
it will return None.
3. fetchmany(n): It will retrieve a number of records from the database. If records are not available
then it will return an empty tuple.
4. rowcount: It is one of the properties of cursor object that return number of rows fetched from the
cursor object.

Observe the below-given code for fetchall() function:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
d=cursor.fetchall()
for r in d:
print(r)

Observe the below-given code for fetchmany(n) function:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
d=cursor.fetchmany(3)
for r in d:
print(r)

The above code will return 3 rows from the database.

Observe the below-given code for fetchone() function:

import mysql.connector as msql


import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")

184 | P a g e
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
time.sleep(3)
print(d)

Parameterized Queries

Sometimes we need to access values as per the user’s input. The query result is based on the values user has
passed. So for that we have this option parameterized queries. There are two ways to use parameterized
queries:
1. with % formatting pattern
2. with {}.format pattern

with % formatting pattern

This pattern takes the general form – f % v, where f is a format and v is the value. Consider the following
code:
import mysql.connector as msql
import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()

#display records more than 80%


cur.execute("select * from students where marks >%s" %(80,))
d=cur.fetchall()
for r in d:
print(r)

#display records having B1 grade


cur.execute("select * from students where grade='%s'" %('B1',))
d=cur.fetchall()
for r in d:
print(r)

with {}.format pattern


In this pattern you can write {} where the value is placed followed by .format(values). Consider the
following code:

import mysql.connector as msql


import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')

185 | P a g e
cur=cn.cursor()
cur.execute("select * from students where marks >{}" .format(80))
d=cur.fetchall()
for r in d:
print(r)
cur.execute("select * from students where grade='{}'".format('B1'))
d=cur.fetchall()
for r in d:
print(r)

Close the connection

Finally, you have to close the established connect using close() function. It will help to clean up the
memory. Observe the following code:

con.close()

WORKSHEETS

L3 – Very Short Answer questions (1 mark)


1. Which package do we import in Python to establish MySQL connectivity ?
Ans. mysql.connector

2. What is the significance of using connect( ) function ?


Ans. connect( ) function is used to connect or establish a connection with MySQL database.

3. What is the role of execute( ) ?


Ans. The role of the execute function is execution of queries which are MySQL queries along
with Python interface.

4. What is the command to install mysql connector ?


Ans. pip install mysql-connector (OR)
pip install mysql-connector-python

5. What is a database connectivity ?


Ans. A database connectivity refers to the connection and communication between an
application and database system.

L3 – Multiple Choice Questions (1 mark)

1. A database _________ controls the connection to an actual database, established from within a
Python program.
(a) database object (b) connection object (c) fetch object (d) query object

186 | P a g e
Ans. (b)

2. The set of records retrieved after executing an SQL query over an established database connection is
called ___________ .
(a) table (b) sqlresult (c) result (d) resultset

Ans. (d)

3. A database _________ is a special control structure that facilitates the row by row processing of
records in the resultset.
(a) fetch (b) table (c) cursor (d) query

Ans. (c )

4. To obtain all the records retrieved, you may use the <cursor>. _______ method.
(a) fetchmany( ) (b) fetchall( ) (c) fetchone( ) (d) fetchmultiple( )
Ans. (b)
5. To reflect the changes made in the database permanently, you need to run <connection>. _______
method.
(a) done (b) reflect (c) commit (d) final
Ans. (c)
6. To run an SQL query within Python, you may use the <cursor>. _______ method.
(a) query (b) execute (c) run (d) None of the above

L2 – Short Answer Questions (2 marks)

1. What are the steps for creating database connectivity applications ?

Ans. To create database connectivity, follow the given steps:


Step 1: Start Python
Step 2: Import mysql.connector
Step 3: Open a connection to the database
Step 4: Create a cursor instance
Step 5: Execute a query
Step 6: Extract data from result set
Step 7. Clean up the environment

2. What is a connection? What is its role?

Ans. A connection (represented by the connection object) is the session between the application
program and database. To do anything with database, one must have a connection object.

3. What is a resultset?

Ans. A result set refers to a logical set of records that are fetched from the database by executing a
187 | P a g e
query and made available to the application program.

4. What is a database cursor?

Ans. A database cursor is a special control structure that facilitates row by row processing of records in
the result set, i.e., the set of records retrieved as per the query.

5. How to retrieve data from a table?

Ans. There are multiple ways to retrieve data:

i. fetchall( ) – fetches all the remaining rows of a query result, current pointer position
forwards
ii. fetchone( ) – fetches the next row as a sequence; returns None when no more data

L1 – Long Answer Questions (3 marks)

1. Write a Python code to connect to a database


Ans.
import mysql.connector
Mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,database=”project”)
Print(mycon)

2. How to create a database in MySQL through Python ?


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor( )
cursor.execute(“create database education”)

3. Write the Python code to display the present databases in MySQL


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“show databases”)
for i in cursor:
print(i)
4. How to create a table in MySQL through Python ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“create table student(admn_no int primary key,sname varchar(30),gender char(2),DOB
date, stream varchar(15), marks float”)

5. Write the Python code to insert data into a table in MYSQL


188 | P a g e
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
ano=int(input(“Enter admission no: “))
n=input(“Enter name: “)
g=input(“Enter gender:”)
dob=input(“Enter DOB: “)
s=input(“Enter stream: “)
m=float(input(“Enter marks:”))
query=”insert into student values({},’{}’,’{}’,’{}’,’{}’,’{}’,{})”.format(ano,n,g,dob,s,m)
cursor.execute(query)
mycon.commit( )

6. How to fetch data in Python from a table in MySQL ?


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“select * from student”)
for row in cursor:
print(row)

7. Write the Python code to update a record in the table


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“update student set marks=67 where admn_no=3456”)
mycon.commit( )

8. Write the Python code to delete a record from the table


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“delete from student where admn_no=3455”)
mycon.commit( )

*************

189 | P a g e

You might also like