DBMS & SQL
DBMS & SQL
Relational
Database
Model
Introductory
Database
Concepts of
Constraints
Database
Database
Management
Common Database
Database Languages
Operations & SQL
Database
Keys
SQL
Operations in SQL
Database Key
Key in a database is defined as a set of attributes to identify each record uniquely in a table. A Key
must be unique and not null.
Classification of Keys:
Key
Date & Time data types: Used to represent date, time, or both in a column. Data is enclosed
with quotes ‘ ’ or “ “.
e.g. - date, datetime, time
String / Text data types: Used to represent text in a column. Data is enclosed with quotes ‘ ’
or “ “.
e.g. –
char(m) – Fixed length character of length m where 1 character takes 1 Byte in memory.
Memory space is wasted if text size is less than m.
varchar(m) – Variable length character allowing maximum number of characters m. It
saves memory allocation for text having lesser size than m.
Query:
Query is a type of SQL commands which accepts tables (relations), columns (fields or attributes)
and conditions or specifications if any and display the output by means of a temporary table which
consists of data represented through fields and records.
Structure of Query:
SELECT < 1, multiple ( comma i.e. , separated) or all columns >
FROM < 1 table or multiple tables ( comma i.e. , separated) in case of join >
WHERE <condition on column(s)>
GROUP BY <1 column>
HAVING < condition on aggregate function on a column only if group by exists >
ORDER BY <0, 1 or more ( comma i.e. , separated) columns >
Note:
I. Among above SELECT and FROM are mandatory statements in a query and all other
statements are optional.
II. SELECT statement contains one or more columns. * should be used to display all columns.
Functions or expressions on columns can also be done.
III. FROM statement contains multiple tables only if columns from more than one tables are
displayed through SELECT statement in case of product or join operations. Here records
can be fetched from multiple tables.
IV. WHERE clause may contain multiple conditions related with logical OR / AND operators.
Logical NOT operator can be used on a condition also.
V. GROUP BY clause is used if statistical records are to be displayed based on a field/column.
In this case SELECT statements should contain GROUP BY field and aggregate function
on another column at least. Once a group is formed individual records cannot be accessed
in the same query.
VI. ORDER BY clause can be used to arrange the output records in ascending (by default) or
descending order of values in one or more columns.
Order of execution of a query
Step 1: Identify table(s) with FROM clause
Step 2: Filter records using WHERE clause
Step 3: Form group if any using GROUP BY clause
Step 4: Filter groups using HAVING clause only if GROUP BY is used
Step 5: Arrange the output records in ascending or descending order using ORDER BY
Step 6: Display the fields mentioned in SELECT clause.
Database Constraints
Rules imposed on the values of one or more columns in the tables are called database constraints.
The database constraints are:
UNIQUE Ensures that all values in a column are different. No two records have
same values in that column.
NOT NULL Ensures that a column can never have NULL values.
PRIMARY KEY Uniquely identify a record. It is a combination of UNIQUE and NOT
NULL.
CHECK Specify the domain of values with certain criteria for a column.
DEFAULT Provides default value for a column when no value is specified.
REFERENCES / Ensures referential integrity between the foreign key of dependent /
FOREIGN KEY referencing table and primary key of independent / referenced table.
DESC DEPT;
or,
CREATE TABLE EMPL
(
EID VARCHAR(6),
ENAME VARCHAR(30) NOT NULL,
GEN CHAR,
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
SALARY DECIMAL(8, 2) ,
MGR_ID VARCHAR(6) ,
DEPT_ID VARCHAR(4) ,
PRIMARY KEY(EID),
CHECK (GEN IN ('M', 'F', 'T')),
CHECK (SALARY BETWEEN 5000.00 AND 300000.00),
FOREIGN KEY(MGR_ID) REFERENCES EMPL(EID),
FOREIGN KEY(DEPT_ID) REFERENCES DEPT(DEPT_ID)
);
DESC EMPL;
Name of tables defined in current database so far.
SHOW TABLES;
INSERT INTO EMPL VALUES ('E0001', 'RITU SEN', 'F', '2002-06-20', 'KOLKATA',
40000.00, NULL, 'D03');
INSERT INTO EMPL VALUES ('E0004', 'ANISHA RAWAT', 'F', '2019-09-04', 'DELHI',
20000.00, 'E0001', 'D03' );
INSERT INTO EMPL VALUES ('E0005', 'SANA KHAN', 'F', '2017-08-31', 'DELHI',
30000.00, 'E0003', 'D01');
C. Write SQL statements for the following queries and display their outputs.
2. Display name and salary of all the employeEs from table EMPL.
SELECT ENAME, SALARY
FROM EMPL;
4. Display DNAME in ascending order of MAX_STRENGTH.
Note:
Sorting in SQL is by default in ascending order of values be it numeric or alphabetical
order. Hence ASC is default keyword and need not be used in ORDER BY statement.
In case of arranging the output of query in descending order of values DESC keyword must
be used in ORDER BY statement.
Comparison operators
= > < >= <= <> !=
6. Display name of employees and salary in descending order of names where DEPT_ID is
not 'D03'.
SOLUTION OUTPUT
SELECT ENAME,
SALARY
FROM EMPL
WHERE DEPT_ID !=
'D03'
ORDER BY ENAME
DESC;
SOLUTION OUTPUT
SELECT EID, ENAME
FROM EMPL
WHERE DOJ > '2015-01-31' ;
Logical Operators
OR AND NOT
Logical operators are used in where clause. AND, OR are binary operations which require 2
conditions. NOT is unary operator which requires one condition only.
AND : c1 and c2 → If both c1 and c2 are true the overall condition is true.
OR : c1 or c2 → If at least one between c1 or c2 are true the overall condition is true.
NOT : not c1 → If c1 is true the overall condition is false and vice versa.
BETWEEN: BETWEEN operator can be used as a substitute of and operation where the minimum
and maximum value is to be checked for a single column.
8. Display the records of those employees whose salary is between 35000 and 45000.
SOLUTION1 SOLUTION2
SELECT * FROM EMPL SELECT * FROM EMPL
WHERE SALARY >=35000 WHERE SALARY BETWEEN
AND SALARY <=45000; 35000 AND 45000;
Checking a list of values
IN: IN operator is a substitute of OR operation(s) among equality checking of a single column with
multiple values.
NOT IN: NOT IN operator is used for non-equality checking of a column with multiple values.
9. Display name and hometown of employees who belong to departments 'D01' or 'D02'.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT ENAME, SELECT ENAME,
HOMETOWN HOMETOWN
FROM EMPL FROM EMPL WHERE
WHERE DEPT_ID = 'D01' DEPT_ID IN ('D01', 'D02');
OR DEPT_ID = 'D02';
10. Display EID and SALARY of employees whose half of salary is neither 10000 nor 20000.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT EID, SALARY SELECT EID, SALARY
FROM EMPL FROM EMPL
WHERE NOT (SALARY/2 = WHERE SALARY/2 NOT
10000 OR SALARY/2 = IN (10000, 20000);
20000);
Wildcard Characters
A string constant to be checked with a value stored in a column may have one or more characters
missing in case of sub string checking. Such placeholder can be of two types:
_ → Replacement or placeholder of exactly one character in the string constant value.
(underscore)
% → Replacement or placeholder of 0 or more characters in the string constant value.
LIKE: A string constant containing one or more wildcard characters can be checked for equality
with LIKE operator only, not =.
NOT LIKE: Likewise NOT LIKE operator checks inequality checking with a string constant
containing one or more wildcard characters. It cannot be done using <> or !=.
11. List the name of employees whose name starts with 'S' and have length at least 5.
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE 'S____%';
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE '%N'
AND ENAME NOT LIKE '%M%';
NULL checking
IS: IS is a special operator which is used to check absence of value i.e. NULL in a column as no
other comparison operator can be used on NULL values.
IS NOT: Likewise, IS NOT is used to check the presence of values i.e. NOT NULL in a column.
13. Print ENAME and DEPT_ID of employees who do not have manager i.e. MGR_ID is blank.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NULL;
14. Print ENAME and DEPT_ID of employees who have manager i.e. MGR_ID is not empty.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NOT NULL;
16. List the name of places which are hometown of any employee. (No duplicate values)
SOLUTION OUTPUT
SELECT DISTINCT
HOMETOWN
FROM EMPL;
Aggregate functions
GROUP BY: GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Once the group is formed individual records cannot be accessed in that query. Several
clusters or groups are formed based on the number of different values in the GROUP BY column
present in the table.
For example, if GROUP BY is applied on TYPE field of ITEM table 3 groups are formed – Crops
have 2 records, Leaves and Pulses have one record each.
Renaming field and table
AS is an optional keyword to rename a column a table in FROM clause or an expression on
column(s) in SELECT clause. If there is blank space in alias then it must be surrounded by ' ' or '' ''.
Column renaming is done for customized display of query output.
Table renaming is done for giving convenient names to the tables in join operations for
ease of access by programmers.
17. Display the number of distinct DLOC mentioned in table DEPT.
SOLUTION OUTPUT
SELECT COUNT(DISTINCT DLOC) as 'NO. OF
LOCATIONS'
FROM DEPT;
18. Display the earliest and latest DOJ of employees as per EMPL.
SOLUTION OUTPUT
SELECT MIN(DOJ) 'EARLIEST', MAX(DOJ)
'LATEST'
FROM EMPL;
HAVING: It is a conditional statement used along with group by clause only. It compares the
values with the outcome of aggregate functions belonging to each group already formed by
GROUP BY clause.
Difference between WHERE and HAVING:
21. Display the hometowns and no. of employees belonging to them if the headcount per
hometown is at least 2.
SOLUTION OUTPUT
SELECT HOMETOWN, COUNT(EID) 'NO
OF EMPLOYEE'
FROM EMPL
GROUP BY HOMETOWN
HAVING COUNT(EID) >= 2;
22. Display the number of employees working in each DEPT_ID excepting 'D01' where no. of
employees in the DEPT_ID is more than 1.
SOLUTION OUTPUT
SELECT DEPT_ID, COUNT(*) AS 'NO OF
EMPLOYEE'
FROM EMPL
WHERE DEPT_ID != 'D01'
GROUP BY DEPT_ID
HAVING COUNT(*) > 1;
Cartesian Product
Cartesian product is performed on two tables and it produces all the combination of records in both
tables. It does not require any common column.
If tables A, B have m, n columns and p, q records respectively then resultant table A x B has m+n
columns and p x q records.
23. Perform Cartesian Product between EMPL and DEPT.
SOLUTION 1 SOLUTION 2 SOLUTION 3
SELECT * SELECT * SELECT *
FROM EMPL, DEPT; FROM EMPL INNER JOIN FROM EMPL JOIN
DEPT; DEPT;
[RECOMMENDED
STATEMENT]
JOIN
NATURAL JOIN: Natural join is a binary operator which works on two tables. They should have
one column which have same name and domain. It a combination of Cartesian product and a where
clause with equality checking on the common columns.
Other conditions in that query are ANDed with the join condition.
Natural join is mostly done on Foreign key field of one table and Primary key field of
another table.
If tables A, B have m, n columns and p, q records respectively then resultant table has m+n
columns and minimum(p,q) records.
EQUI JOIN: Equi join is a join operation which works on the equality condition of values in two
columns from two tables having similar data type. NATURAL JOIN, EQUI JOIN are said to be
INNER JOIN.
24. Perform Natural Join between these two tables.
SOLUTION 1 SOLUTION 2
SELECT * SELECT *
FROM EMPL NATURAL JOIN FROM EMPL, DEPT
DEPT; WHERE EMPL.DEPT_ID =
DEPT.DEPT_ID;
[RECOMMENDED STATEMENT]
27. Display no. of employees working in those departments whose DLOC is CHENNAI.
SOLUTION OUTPUT
SELECT COUNT(*) 'NO. OF EMPLOYEES'
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DLOC = 'CHENNAI';
28. Display ENAME of employees who have manager along with that display ENAME of their
corresponding manager as well.
SOLUTION OUTPUT
SELECT E.ENAME 'EMPLOYEE', M.ENAME
'MANAGER'
FROM EMPL E, EMPL M
WHERE E.MGR_ID = M.EID;
29. Display ENAME and the amount of bonus to be paid to that employee where bonus = 5000 +
5% of SALARY.
SOLUTION OUTPUT
SELECT ENAME, SALARY,
5000 + 0.05 * SALARY 'BONUS'
FROM EMPL;
DESC DEPT;
3. Modify the datatype of SALARY in table EMPL to an integer of length 6 and drop the existing
check constraint.
SOLUTION OUTPUT
ALTER TABLE EMPL
MODIFY SALARY INT(6);
DESC EMPL;
Questions ;
Q. No. 1 to 20 are MCQs of 1 mark each
18. Assertion(A): DBMS is an application package which arranges the data in orderly
manner in a tabular form.
Reason(R): It is an interface between database and the user. It allows the users to
access and perform various operations on stored data using some tools.
19. Assertion(A): Aggregate function AVG() calculates the average of a set of values
and produces a single value as result.
Reason(R): The aggregate functions are used to perform some basic calculations
like sum, max, min, etc on a set of numbers.
20. Assertion(A): While inserting records in EMP table, value of DateOfBirth field
must be enclosed withing quotes ‘ ‘.
Reasoning(R): Date is represented as char / varchar always.
22. What do you mean by referential integrity? Explain with suitable example.
23. Write MySQL statement to create a table named REMEDIAL based on the
following specification:
Table: REMEDIAL
Attribute Data type Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY
28. A MySQL table, sales have 10 rows. The following queries were executed on
the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
10
32. Write output of the SQL queries based on the following tables Projects and
Employee:
i. Define CID in CUSTOMER table as Foreign Key that refers to CID i.e.
Primary Key of COMPANY table.
ii. Display the ‘CUSTOMER NAME’, ‘PRODUCT NAME’ who have purchased
any product from the ‘COMPANY NAME’ ‘SONY’.
iii. Increase the QTY by 15 for the products with PRICE below 40,000.
34. Consider the GAMES table and answer the following questions:
Abhay wants to do the following operations on the STORE table. Please help him
to do by writing appropriate SQL statements.
i. Insert the following record in the STORE table:
(2010, Notebook, 23, NULL)
ii. Add a new column price with data type as decimal.
36. What do you mean b y CHECK constraint and DEFAULT constraint? Explain
with suitable example.
37. Consider the following tables and answer the questions below:
i. What will be the degree and cardinality of the resultant table after performing
Cartesian Product between PRODUCT and CLIENT?
ii. What will be the degree and cardinality of the resultant table after performing
NATURAL JOIN between PRODUCT and CLIENT?
iii. Are these values same? What can be the reason for this?
38. i. Write down the purpose of using aggregate functions in MySql.
ii. Give example of any two aggregate functions and their purposes.
iii. Can we use aggregate functions without GROUP BY clause? Justify.
40. i. Name the aggregate functions valid on a column of DATE data type.
ii. Suggest a keyword for renaming an attribute or a table in MySql.
iii. Write down the syntax of representing the common column CODE while
performing Equi Join between two tables GAME and USER.
ii. Consider the following table and find the output of the following queries:
ii. Display the values in TYPE column of the table CAR after removing the
duplicate values from the output.
select ___________ TYPE from CAR;
iii. Display MODEL, PRICE, COLOUR from CAR whose COLOUR is neither
RED nor BLUE.
select MODEL, PRICE, COLOUR from CAR
where COLOUR _________ (‘RED’, ‘BLUE’);
(i) Display the total PERIODS for each SUBJECT from SCHOOL table.
(ii) Display TEACHERNAME, GENDER from the tables SCHOOL and ADMIN
whose DESIGNATION is ‘COORDINATOR’.
49. Consider the table Fees mentioned in Q. No. 48 and answer the following
questions:
ii. Increase the second quarter fee of class 12th students by 50.
iii. Delete the record of student with Rollno-1212
iv. Aman wants to display the schema (structure) of Fees table. Which command
will he use from the following:
a) CREATE b) ALTER c) SHOW d) DESCRIBE
50. Sagar, a cloth merchant creates a table CLIENT with a set of records to maintain
the client’s order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the
table, he has entered data of 7 clients in the table.
i. Write the statements to Update a record present in the table with data for
Qtr2 = 200, Qtr3 = 600 , total = sum of all Qtrs where the Client_ID is C660.
ii. Delete all records where total is between 500 to 900.
iii. Make changes in ClientName with data type varchar(20) and not null
constraint.
iv. Remove the column Total from the CLIENT table.
_________
SOLUTIONS
1. B 2. a 3. d 4. c 5. d
6. a 7. b 8. d 9. a 10. b
11. d 12. c 13. b 14. a 15. False
16. False 17. a 18. a 19. b 20. c
21. a) Degree - no. of attributes in a table, Cardinality – no. of records in a table.
b) Degree – 4, cardinality – 6
22. Foreign key of one table refers to the Primary key of another table.
23. CREATE TABLE REMEDIAL
(
SNAME VARCHAR(20) NOT NULL,
ROLL INT(5) UNIQUE,
FEES FLOAT(7,2),
ADMN INT(5) PRIMARY KEY
);
24. a. USE OFFICE;
b. DESC EMPL; or DESCRIBE EMPL;
25. a. PNO as unique throughout table and not null.
b. PNAME, SPORTS, SALARY.
26. a. ALTER TABLE MOTOR MODIFY MODEL VARCHAR(30) NOT NULL;
b. UPDATE MOTOR SET PRICE = PRICE * 1.20 WHERE BRAND = ‘TATA’;
27. DML - INSERT, UPDATE
DDL - ALTER, DROP
28. Count(*) will return the number of records in the table sales. Count(discount) will
return the number of records having not null values in the discount field of sales
table.
29. GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Groups are formed based on the number of different values in the
GROUP BY column present in the table.
30. In Natural Join the common attribute between two tables appears only once. Where
as in Equi Join the common attribute appears as it is i.e. twice. Hence these
common attributes are accessed as table_name.attribute in the query to resolve the
conflict.
31. i.
Name Project
Ranjan P01
Muneera P01
Alex P02
Akhtar P04
Satyansh P04
ii.
Name Salary
Ranjan 150000
Akhtar 125000
iii.
min(DOJ) max(DOB)
2015-01-21 1996-11-15
32. i.
Project count(*)
P01 2
P04 2
P02 1
ii.
PID PName EID
P01 Road 102 Carpenting E01
P04 Footover Bridge K-13 E02
P01 Road 102 Carpenting E03
P02 Civil Lines Parking E04
P04 Footover Bridge K-13 E05
iii.
avg(Salary)
135000
36. CHECK – Ensure that the attribute contains only permissible set of values.
DEFAULT – Ensure the default value is inserted if no value is mentioned.
e.g. -
CREATE TABLE STOCK
(
SNO INT PRIMARY KEY,
SNAME VARCHAR(20),
LOCATION VARCHAR(15) DEFAULT ‘BANGALORE’,
PRICE FLOAT(7,2) CHECK (PRICE BETWEEN 0.00 AND 10000.00)
)
37. i. After Cartesian product, Degree = 8, Cardinality = 25
ii. After natural join, Degree = 7, Cardinality = 5
iii. No, because cartesian product is the all-possible combination of tuples between
two tables. Where as Natural join selects only those tuples for whom the values of
the common attributes are same.
38. i. Aggregate functions perform calculation on a set of values, and returns a single
value. If used with GROUP BY clause, it returns one value for each group.
SUM() - returns the total sum of a numerical column
MAX() - returns the largest value within the selected column
ii. Yes. Then it returns a single value for the selected attribute by considering all the
records in that table.
39. i. NULL is said to be absence of any value in an attribute. NULL cannot participate
in any operation.
ii. IS
iii. COMMIT
40. i. MAX(), MIN(), COUNT()
ii. AS
iii. SELECT * FROM GAME G, USER U WHERE G.CODE=U,CODE;
41. i. WHERE clause allows to filter data from individual rows of a table based on
certain conditions. In contrast, the HAVING clause allows to filter data from a
group of rows in a query based on conditions involving aggregate functions.
ii.
a)
SEX AVG(SALARY)
M 68666
F 65000
b)
SUBJECT COUNT(*)
Computer Science 2
c)
SUBJECT MIN(SALARY)
Computer Science 75000
English 55000
Economics 71000
42. i. DELETE is used for deleting records from a table. DROP is used to delete the
entire schema of any database object like table.
e.g. –
DELETE FROM STUDENT WHERE ROLL = 5;
DROP TABLE STUDENT;
ii.
E_CODE NAME E_CODE LOCATION
E01 ASHISH E05 MUMBAI
E02 SURESH E05 MUMBAI
iii. d. Cross join
43. i. databases
ii. distinct
iii. not in
iv. count
v. as
44. i. Data integrity, data security
ii. Char data type stores data of fixed length, whereas the Varchar data type stores
variable length data. Varchar is preferable as it is more flexible for data of any size.
iii. It can represent 7 digit real number with 3 digits in the right of decimal point.
45. i. A self-join is a regular join, but the table is joined with itself.
SELECT * FROM EMP A, EMP B where A.ID = B.ID;
ii.
(a) TABLE
(b) DEFAULT
(c) CHECK
46. i.
ITEM_NAME MAX(PRICE) COUNT(*)
Personal Computer 37000 3
Laptop 57000 2
ii.
CNAME MANUFACTURER
N Roy PQR
R Singh XYZ
R Pandey COMP
C Sharma PQR
K Agarwal ABC
iii.
ITEM_NAME PRICE*100
Personal Computer 3500000
Laptop 5500000
iv.
City
Delhi
Mumbai
Bangalore
To save the current transactions of inserting, updating and deleting data we use:
mydb.commit()
6. close() to close the connection and clean up the environment
mydb.close()
1. To establish a connection with MySQL from Python which of the following functions is used?
(a) connection()
(b) connect()
(c) open()
(d) cursor()
3. To establish a connection between Python and sql database, connect() is used. Which of the
following arguments may not necessarily be given while calling connect()?
(a) host
(b) database
(c) user
(d) password
6. To make the changes made by any SQL Queries permanently in database, which function is used
after execution of the query?
(a) save()
(b) commit()
(c) execute()
(d) dump()
9. To get all the records from result set, you may use ___________.
(a) cursor.fetchmany()
(b) cursor.fetchall()
(c) cursor.fetchone()
(d) cursor.execute()
10. Which of the following is not a valid method to fetch records from database in python.
(a) fetchmany()
(b) fetchone()
(c) fetchmulti()
(d) fetchall()
11. Which attribute of cursor is used to get number of records stored in cursor (Assumeg cursor
name is mycursor)?
(a) mycursor.count
(b) mycursor.row_count
(c) mycursor.records
(d) mycursor.rowcount
12. Which of the following package must be imported in Python to create a database connectivity
application?
(a) mysql.connector
(b) mysql.connect
(c) sql.connector
(d) sql.execute
13. Which of the following method reflects the changes made in database permanently?
(a) <connection>.done()
(b) <connection>.final()
(c) <connection>.reflect()
(d) <connection>.commit()
14. Which method of cursor class is used to fetch limited rows from the table?
(a) cursor.fetchsize(SIZE)
(b) cursor.fetchmany(SIZE)
(c) cursor.fetchall(SIZE)
(d) cursor.fetchonly(SIZE)
15. Which method of cursor class is used to get the number of rows affected after any of
the Insert/update/delete database operation executed from Python?
(a) cursor.rowcount
(b) cursor.getaffectedcount
(c) cursor.rowscount
(d) cursor.rcount
16. Which of the following component acts as a container to hold the data returned from the query:
(a) table
(b) cursor
(c) resultset
(d) container
17. To get the next record from the result set, we may use .
(a) cursor.fetch(next)
(b) cursor.fetchmany()
(c) cursor.fetchall()
(d) cursor.fetchone()
18. SQL command is passed to which function to run after establishment of the connection
between python and database
(a) cursor()
(b) execute()
(c) connection()
(d) fetchall()
19. Which of the following function is used to close the connection between python and database?
(a) cursor.close()
(b) is.close()
(c) connection.close()
(d) execute.close()
2 Marks Questions
1. Which method we use to establish the connection and clear the connection?
Ans: connect() and close() methods with connection object.
3 Marks Questions
1. What is a result set? Give example with coding.
Ans: A result set refers to a logical set of records that are fetched from the database by executing a
query and made available to the application-program.
Eg: myresult = mycursor.fetchall()
2. Which package must be imported in Python to create a database connectivity application? Give
example with coding.
Ans:There are multiple packages available through which database connectivity applications
can be created in Python. One such package is mysql.connector.PyMySQL, mysqlclient, etc. can
also be used for connectivity.
Eg: import mysql.connector
4. Write the python script to read the whole data from the table emp and display all the records.
Ans: import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
print (mydb)
mycursor=mydb.cursor()
numrow=mycursor.execute("select * from student")
print(mycursor.fetchall())
mydb.close()
Help your friend Sonia in writing the following missing statements to complete the code:-
Ans:
Statement 1: mysql.connector
Statement 2: mydb.cursor()
Statement 3: mydb.commit()
Statement 4: mydb.close()
2. Avni is trying to connect Python with MySQL for her project. Help her to write the python
statement on the following:
i. Name the library, which should be imported to connect MySQL with Python.
ii. Name the function, used to run SQL query in Python.
iii. Name the function required to make the changes permanent.
iv. Name the fuction to clear the environment.
Ans:
i. mysql.connector
ii. execute()
iii. commit()
iv. close()
3. Your friend Jagdish is writing a code to fetch data from a database Shop and table name Products
using Python. He has written incomplete code. You have to help him to write complete code:
import __________ as m # Statement-1
object1 = m.connect(host="localhost", user="root", password="root", database="Shop")
object2 = object1._________ # Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
object2._________(query) # Statement-3
__________.close() # Statement-4
Ans:
Statement 1: mysql.connector
Statement 2: cursor()
Statement 3: execute()
Statement 4: object1
4. The code given below reads the following record from Table named Employee and display those
record salary >= 30000 and <= 90000:
Empno – integer
EName – string
Desig – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is Password
The table exists in a MYSQL database named Bank.
Write the following missing statements to complete the code on behalf of your friend Sandeep:
Statement 1 – to form the cursor object
Statement 2 – to query string.
Statement 3 - to execute the query that extracts records of those Employees whose salary >=30000
and <=90000.
Statement 4 - to close the connection.
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='Password',database='bank')
mycursor=_________________ # statement1
mycursor.________________ #statement 2
data= __________________ # statement 3
for x in data:
print(x)
______________ # statement 4
Ans:
Statement 1: mydb.cursor()
Statement 2: execute('''SELECT * FROM Employee WHERE salary >= 30000 and salary <=
90000;''')
Statement 3: mycursor.fetchall()
Statement 4: mydb.close()
5. The code given below inserts the following record in the table Emp:
Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be accepted
from the user.
Help your friend in writing the following missing statements to complete the code:
Statement 1 – to create a connection
Statement 2 – to form the cursor object
Statement 3 – to execute the command that inserts the record in the table Emp.
Statement 4 - to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
mycursor=_________________ #Statement 1
eno=int(input("Enter Employee Number: "))
Ename=input("Enter Employee Name: ")
Designation=input("Enter Designation: "))
Salary=int(input("Enter Salary: "))
Bonus=int(input("Enter Bonus: "))
querry="insert into emp values({},'{}',{},{})".format(eno,ename,designation,bonus)
______________________ #Statement 2
______________________ # Statement 3
print("Employee Data Added successfully")
Ans:
Statement 1: con1= mysql.connect(host="localhost",user="root", password="tiger",
database="Employee")
Statement 2: con1.cursor()
Statement 3: mycursor.execute(querry)
Statement 4: con1.commit()
5 Marks Questions
1. Write the steps to perform an Insert query in database connectivity application. Table Student
values are rollno, name, age (10,’Ashok’,26).
Ans:
Statement 1: c
Statement 2: con.cursor()
Statement 3: mycursor.execute(sql)
Statement 3: mycursor.commit()
Statement 3: con.close()
3. Write the python function to accept the name as parameter and find out whether record present
in the table or not. Table Student columns are rollno, name, age.
Ans:
Statement 1: import mysql.connector as mycon
Statement 2: mycursor.commit()
Statement 3: execute
Statement 4: mycursor.fetchall()
Statement 5: mydb