Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
2K views

Computer-Science-Class-12 DBMS NOTES

The document discusses database management systems and relational databases. It defines what a DBMS is and provides examples of common DBMS software. It also explains key concepts in relational databases like tables, rows, columns, primary keys, and foreign keys.

Uploaded by

Prince
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views

Computer-Science-Class-12 DBMS NOTES

The document discusses database management systems and relational databases. It defines what a DBMS is and provides examples of common DBMS software. It also explains key concepts in relational databases like tables, rows, columns, primary keys, and foreign keys.

Uploaded by

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

JOHNSON GRAMMAR SCHOOL

[CBSE]
DBMS-DATABASE MANAGEMENT SYSTEM
DBMS:
A database management system (DBMS) is a collection of interrelated data and a set of
programs to access those data. The collection of data, usually referred to as the
database, contains information relevant to an enterprise. The DBMS provides a way to
store and retrieve database information that is both convenient and efficient.
Keeping organizational information in a file- processing system has a number of major
disadvantages like:
a) Data redundancy and inconsistency
b) Difficulty in accessing data
c) Data isolation
d) Integrity problems
e) Atomicity problems
f) Concurrent access anomalies
g) Security problems
These difficulties among others, prompted the development of database systems.
● Database systems are designed to manage large bodies of information.
● Management of data involves both defining structures for storage of information
and providing mechanisms for the manipulation of information.
● The database system also must ensure the safety of the information stored,
despite system crashes or attempts at unauthorized access. If data are to be
shared among several users, the system must avoid possible anomalous
results.
● DBMS lets users to create a database, store, manage, update/modify and retrieve
data from that database by users or application programs.
Some examples of open source and commercial DBMS include MySQL, Oracle,
PostgreSQL, SQL Server, Microsoft Access, MongoDB.
Database systems are widely used. Some representative applications are :
a) Banking
b) Airlines
c) Universities
d) Telecommunications
e) Sales
f) Finance, etc.
A data model describes the structure of the database, including how data are defined
and represented, relationships among data, and the constraints.
Database schema: Database Schema is the design of a database. It is the skeleton of the
database that represents the structure (table names and their fields/columns), the type
of data each column can hold, constraints on the data to be stored (if any), and the
relationships among the tables.
Database schema is also called the visual or logical architecture as it tells us how the
data are organized in a database.
Data constraint: Restrictions or limitations are put on the type of data that can be
inserted in one or more columns of a table to ensure accuracy and reliability of data in
the database.
Meta – Data or Dictionary: A database catalog or dictionary that has data about data.
Database instance: The state of database at any time, after loading of data. A database
schema can have different instances at different times.
Query: A query is a request to a database for obtaining information in a desired way.
Data Manipulation: Modification of database consists of three operations viz. Insertion,
Deletion or Update.
Database engine: Database engine is the underlying component or set of programs used
by a DBMS to create database and handle various queries for data retrieval and
manipulation.

Relational model:
The relational model uses a collection of tables to represent both data and the
relationships among those data.
Each table has multiple columns, and each column has a unique name. The relational
model is an example of a record – based model.
Record- based models are so named because the database is structured in fixed- format
records of several types. Each table contains records of particular type. Each record type
defines a fixed number of fields/attributes.
The columns of the table correspond to the attributes of the record type.
A row in a table represents a relationship among a set of values. The relational data
model is the most widely used data model.
Other types of data models include object-oriented data model, entity-relationship data
model, document model and hierarchical data model.
Relation: A Relation is logically related data organized in the form of tables.
Attribute/ Field: Column of a table is called Attribute or Field.
Tuple/ Entity/ Record: Rows of a table is called Tuple or Record.
Domain: It is collection of values from which the value is derived for a column.
Degree - Number of columns (attributes) in a table.
Cardinality - Number of rows (Records) in a table.

Primary Key – A primary is a column or set of columns in a table that uniquely


identifies tuples (rows) in that table.

Candidate Key –It is an attribute or a set of attributes or keys participating for Primary
Key, to uniquely identify each record in that table.

Alternate Key – Out of all candidate keys, only one gets selected as primary key,
remaining keys are known as alternate or secondary keys.

Foreign Key – Foreign keys are the columns of a table that points to the primary key of
another table.
STRUCTURED QUERY LANGUAGE(SQL)
Structured Query Language: introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints
(not null, unique, primary key), create database, use database, show databases,
drop database, show tables, create table, describe table.

1.1 What is SQL?


SQL(Structured Query Language) is a language that is used to manage data that is
held in a relational database management system. It uses tables to manipulate and
retrieve information from databases for analysis.
By using SQL commands, one can search for any data in the database and
perform other functions like creating tables, adding records, modifying data, removing
rows, dropping tables etc.
1.2 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
1.3 ADVANTAGES OF SQL
There are the following advantages of SQL:
● High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
● No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
● Well defined standards
Long established are used by the SQL databases that are being used by ISO and ANSI.
● Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
● Interactive language
SQL is a domain language used to communicate with the database. It is also used to
receive answers to the complex questions in seconds.
● Multiple data view
Using the SQL language, the users can make different views of the database structure

1.4 SQL Commands


SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

1.5 Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1.5.1 DDL or Data Definition Language


DDL or Data Definition Language actually consists of the SQL commands that can be used
to define the database schema. It simply deals with descriptions of the database schema
and is used to create and modify the structure of database objects in the database. DDL
is
a set of SQL commands used to create, modify, and delete database structures but not
data.

List of DDL commands:


CREATE: This command is used to create the database or its objects (like table,
index, function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed.
COMMENT: This is used to add comments to the data dictionary.
RENAME: This is used to rename an object existing in the database.

1.5.2 DML (Data Manipulation Language):


The SQL commands that deals with the manipulation of data present in the database
belong to DML or Data Manipulation Language and this includes most of the SQL
statements. It is the component of the SQL statement that controls access to data and to
the database. Basically, DCL statements are grouped with DML statements.
List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.
Difference between DDL and DML:
DDL DML
It stands for Data Definition It stands for Data
Language. Manipulation Language.

It is used to create database


schema and can be used to
define some constraints as It is used to add, retrieve or
well. update the data.

It basically defines the It add or update the row of


column (Attributes) of the the table. These rows are
table. called as tuple.
1.6 DATATYPES

⮚ Text Data types


Char(size) – fixed length of size bytes
Varchar(size)-variable length of size bytes
Varchar2(size)-variable length of size bytes

⮚ Number Data types


Integer(size)or Int- It represents a number without decimal point
Float(Size)-It represents a floating point number
Real-Same as float but no size argument is used

➢ Date data type


Date , Time
1.7 CONSTRAINT
A Constraint is a condition or check applicable on a field or set of fields.
Types of Constraints:

⮚ Unique Constraint :-This ensures that no rows have the same value in the
specified column(s)
Syntax:
Create table EMP (ecode integer unique, ename char(20),sex char(1),grade
char(2));
Unique constraint applied on ecode of EMP table ensures that no rows have the same
ecode value

⮚ Primary key Constraint:- This declares a column as the primary key of the table
This is similar to unique constraint except that one column (or one group of
columns)can be applied in this constraint .
The primary key cannot allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table
is created:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (ID));

⮚ Not null:-This constraint ensures column should not be NULL


Syntax:
Create table EMP(ecode integer Not null unique, ename char(20),sex char(1),grade
char(2));

1.8 DATABASE COMMANDS IN MYSQL

⮚ CREATE DATABASE
CREATE DATABASE is the SQL command used for creating a database in MySQL.
Imagine you need to create a database with name “movies”. You can create a database
in MySQL by executing following SQL command
Syntax: mysql>CREATE DATABASE movies;

⮚ SHOW DATABASES
You can see list of existing databases by running following SQL command.
Syntax: mysql>SHOW DATABASES;

⮚ USE
You can use SQL command USE to select a particular database.
Syntax: mysql>USE database_name;

⮚ DROP DATABASE
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax :mysql>DROP DATABASE database_name;

CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Syntax: CREATE TABLE table_name ( column1 datatype, column2
datatype, column3 datatype,......);
Example: The following example creates a table called "Persons" that contains five
columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

⮚ SHOW TABLES;
We can get the number of table information of a database using the following
statement:
mysql> SHOW TABLES;

⮚ DESCRIBE TABLE
Use the DESCRIBE command to show the structure of the table, such as column names,
constraints on column names, etc. The DESC command is a short form of the DESCRIBE
command. Both DESCRIBE and DESC commands are equivalent.
Syntax The following are the syntax to display the table structure:
mysql> DESCRIBE | DESC table_name;

ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.

ALTER TABLE - ADD Column/Attribute To add a column in a table, use the following
syntax:

ALTER TABLE table_name ADD column_name datatype;

Example ALTER TABLE Customers ADD Email varchar(255);

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax

ALTER TABLE table_name DROP COLUMN

column_name; Example ALTER TABLE Customers

DROP COLUMN Email; SQL PRIMARY KEY on ALTER

TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
ALTER TABLE table_name ADD PRIMARY KEY (Column_name);

Example ALTER TABLE Persons ADD PRIMARY KEY (ID);

DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE table_name DROP PRIMARY KEY;

Example : ALTER TABLE Persons DROP PRIMARY KEY;

The SQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a database.

Syntax DROP TABLE table_name;

DROP TABLE Shippers;

INSERT INTO Statement:


The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax:

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify
the column names in the SQL query. However, make sure the order of the values is in
the same order as the columns in the table. Here, the INSERT INTO syntax would be as
follows:

INSERT INTO table_name VALUES (value1, value2, value3, ...);

The SQL DELETE Statement:


The DELETE statement is used to delete existing records in a table.

DELETE Syntax:
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the
DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you
omit the WHERE clause, all records in the table will be deleted!

The following SQL statement deletes all rows in the "Customers" table, without deleting
the table:

DELETE FROM Customers;

The SQL SELECT Statement


The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-

set.

SELECT Syntax: SELECT column1, column2, ... FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

The SQL WHERE Clause:


The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

WHERE Syntax: SELECT column1, column2, ...FROM table_name WHERE condition;

Operators in The WHERE Clause

The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 184
<= Less than or equal

<> Not equal. Note: In some versions of SQL this


operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a


column

The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

● The AND operator displays a record if all the conditions separated by AND are TRUE.
● The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax

SELECT column1, column2, ...

FROM table_name

WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax

SELECT column1, column2, ...

FROM table_name

WHERE condition1 OR condition2 OR condition3 ...;

NOT Syntax

SELECT column1, column2, ...

FROM table_name

WHERE NOT condition;


The SQL IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name IN (value1, value2, ...);

or:

SELECT column_name(s)

FROM table_name

WHERE column_name IN (SELECT STATEMENT);

The SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name BETWEEN value1 AND value2;

The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax

SELECT column1, column2, ...

FROM table_name

ORDER BY column1, column2, ... ASC|DESC;

Example

SELECT * FROM Customers

ORDER BY Country;

ORDER BY DESC Example

The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:

SELECT * FROM Customers

ORDER BY Country DESC;

ORDER BY Several Columns Example

The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" and the "CustomerName" column. This means that it orders by Country,
but if some rows have the same Country, it orders them by CustomerName:

Eg: SELECT * FROM Customers ORDER BY Country, CustomerName;

SQL Aliases

SQL aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.

Alias Column Syntax: SELECT column_name AS alias_name FROM table_name;

Alias Table

Syntax: SELECT column_name(s) FROM table_name AS alias_name;


The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...

WHERE condition;

UPDATE Table

The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.

UPDATE Customers

SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'

WHERE CustomerID = 1;

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.

SELECT DISTINCT Syntax:

SELECT DISTINCT column1, column2, ...FROM table_name;

SELECT Example Without DISTINCT

The following SQL statement selects all (including the duplicates) values from the
"Country" column in the "Customers" table:

Eg: SELECT Country FROM Customers;

Now, let us use the SELECT DISTINCT statement

and see the result.

SELECT DISTINCT Examples

The following SQL statement selects only the DISTINCT values from the "Country"
column in the "Customers" table:
SELECT DISTINCT Country FROM Customers;

The following SQL statement lists the number of different (distinct) customer countries:

SELECT COUNT(DISTINCT Country) FROM Customers;

The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.

There are two wildcards often used in conjunction with the LIKE operator:

● The percent sign (%) represents zero, one, or multiple characters


● The underscore sign (_) represents one, single character

The percent sign and the underscore can also be used in combinations!

LIKE Syntax

SELECT column1, column2, ...

FROM table_name

WHERE columnN LIKE pattern;

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length

WHERE CustomerName LIKE 'a %' Finds any values that start with "a" and are at
least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
What is a NULL Value?

A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record


without adding a value to this field. Then, the field will be saved with a NULL value.

How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax

SELECT column_names

FROM table_name

WHERE column_name IS NULL;

IS NOT NULL Syntax

SELECT column_names

FROM table_name

WHERE column_name IS NOT NULL;

The IS NULL Operator

The IS NULL operator is used to test for empty values (NULL values).

The following SQL lists all customers with a NULL value in the "Address" field:

SELECT CustomerName, ContactName, Address

FROM Customers

WHERE Address IS NULL;

The IS NOT NULL Operator

The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address

FROM Customers

WHERE Address IS NOT NULL;

Aggregate (Group) function


● Aggregate functions are the functions that operate on a set of rows to give one
result per group.
● These sets of rows on which group function is applied may be the whole table or
the table split into groups.
Types of Group Functions

Function Description

sum() Find the sum of numeric values

avg() Find the average of numeric values

count() Counts the number of rows in a table

max() Find the maximum among all the values in a column

min() Find the minimum among all the values in a column


Remember the following points about group functions:
● All group functions,except count(*) ignore NULL values
● Functions -sum(),avg() are used with NUMERIC data.
● Functions -min() and max() can be used with any data type
Example:
Consider the following table employee
Q: Find the sum, average, minimum, maximum value of salaries of employees in the
employee table

Count() function
Count () has got three formats:
Count(*)
This function returns the number of rows in the table that satisfy the criteria of select
statement.
In its counting, it includes duplicate rows and rows with NULL values in any of the
column
Example:
Q: Count the number of employees in the employee table.

Count(<col name>)
● This function returns the number of not null values in the specified column, but
includes duplicate values in counting
Example
Q; count the number of grades of employees in the employee table.

Count(DISTINCT <col name>)


This function returns the number of unique, not null values in the specified column.
Example
Q Count the number of different grades of the employee

Grouping Records (Group by clause)


 To divide the rows in a table into smaller groups of information, group by clause
is used.
 It combines all identical rows in a group of fields.
 A column name is used for grouping
Syntax;-
SELECT [DISTINCT] <COL LIST> FROM <TABLE NAME>
[WHERE <CONDITION>]
[GROUP BY < GROUP BY EXPR>]
[HAVING <CONDITION>]
[ORDER BY <COL NAME>/<EXPR> ASC/DESC];
NOTE -
● Group by expression specifies the columns whose values determine the basics for
grouping rows
● WHERE clause is always before GROUP BY if required.
Example
Q. Display the no of employees in each zone.

Q. Display the no of employees in each zone whose salary is greater than 32000
Having clause
● This clause is used to restrict rows resulting after grouping.
● Steps followed in execution of select with group by and having clause-
1. Rows are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with Having clauses are displayed.
Example
Q. Display only whose departments with sum of salaries whose total salary is greater
than 70000

Cartesian Product (Cross Join or unrestricted join)


 Returns all the rows in the two tables listed in the query.
 Each row of the first table is paired with all the rows in the second table.
 This happens when there is no relationship between two tables.
 It is rarely useful.

Example- Consider the following tables


Q: To display the name of the employees and their department name

Joins in MySQL
● A join is used when data from two or more tables is required.
● Rows in one table can be joined to the rows in another table based on the
common values existing in corresponding columns of two tables.
● Joins are used to retrieve data from tables related to each other with primary-
foreign key relationships.
● There are many types of join
Equi join
● Specified columns from the joining tables are checked for equality.
● Values from joining tables are retrieved only if the condition in where clause is
satisfied.
SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>,...., <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;

Q: to display the name of the employee and their department


Note-
To join n tables together minimum of n-1 join conditions are to be satisfied.
Results of Equi joins are the same as simple joins or inner joins. Inner join (simply join)
uses on clause.
You should always qualify the columns when joining tables having the same name as
corresponding columns. To qualify the columns we use “.” (dot) operator.

Natural Join
This clause is based on all the columns in the two tables that have the same name.
It selects the rows from two tables that have equal values in the matched columns.
SYNTAX:-

SELECT [column_names |
*] FROM table_name1
NATURAL JOIN
table_name2;

Example- consider the same tables employee and department.


Q : To display the name of employee and department of all employee

Note-No need to specify the column names to join. Works with same column name in
both the tables. The Resulting table has unique columns.
Interface Python with SQL database
Contents:
 Connecting SQL with Python
 Creating database connectivity applications
 Performing insert, delete, update,delete queries
 Display data by using fetchone(), fetchall(), fetchmany (),
rowcount()

Database connectivity
Database connectivity refers to connection and communication between an application
and a database system.
The term “front-end” refers to the user interface, while “back-end” means the server,
application and database that work behind the scenes to deliver information to the user.
 Mysql.connector- Library or package to connect from python to MySQL.
Before we connect the program with mysql , we need to install connectivity package
named mysql-connector- python
 Command to install connectivity package:- pip install mysql-connector-python
 Command to import connector:- import mysql.connector
 Steps for python MySQL connectivity

1 . Install Python
2. Install MySQL
3. Open Command prompt
4. Switch on internet connection
5. Type pip install mysql-connector-python and execute
6. Open python IDLE
7. import mysql.connector

Steps for creating database connectivity applications:

1. Start Python- start python editor to create our own python script.

2. Import mysql.connector package

Use the following statement for this.


import mysql.connector or

import mysql.connector as Con

3. Establishing a connection to Mysql DATABASE.

We need to establish a connection to a mysql database using connect () function of


mysql.connector package.

The connect statement creates a connection to the mysql server and returns a
MySQL connection object.

Syntax:

<Connection object> = mysql.connector.connect (host=<hostname>,


user=<username>, passwd:<password>, database=<dbname>)

For eg: import mysql.connector

con=mysql.connector.connect(host=”localhost”,user=”root”, passwd=” “)

4. Creating a cursor Object

It is a useful control structure of database connectivity. It will let us


execute all the queries we need. Cursor stores all the data as a temporary
container of returned data and allows traversal so that we can fetch data one
row at a time from cursor. Cursors are created by the connection.cursor()
method.

Syntax:

<cursor object>=<connectionobject>.cursor()

Eg: cursor=con.cursor()

5. Execute SQL query:

We can execute SQL query using execute() function .

Syntax: <cursor object>.execute(SQL QUERY)

Eg: cursor.execute(“select * from data”)

The above code will execute the sql query and store the retrieved records
(resultset) in the cursor object(cursor).
Result set refers to a logical set of records that are fetched from the database
by executing an sql query and made available in the program.

6. Extract data from Result set:

The records retrieved from the database using SQL select query has to be
extracted as record from the result set. We can extract data from the result
set using the following fetch () function.

fetchall()

fetchone()

fetchmany()

 Multiple ways to retrieve data:


 fetchall()- Fetches all (remaining) rows of a query result,
returning them as a sequence of sequences (e.g. a list of
tuples) .
 fetchone()-Fetches the next row of a query result set, returning
a single sequence or None when no more data is available
 fetchmany (size)-Fetches the next set of rows of a query
result, returning a sequence of sequences. It will return
number of rows that matches to the size argument.

Functions to execute SQL queries

# TO CREATE DATABASE SCHOOL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE SCHOOL")

# SHOW DATABASE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system")
mycursor=mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print (x)

# TO CREATE A TABLE IN MYSQL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="s
ystem",database="student")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE FEES (ROLLNO INT,NAME
VARCHAR(20),AMOUNT INT);")

# TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
#TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE

mydb=mysql.connector.connect(host="localhost",user="root",passwd="system"
,database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC STUDENT")
for x in mycursor:
print(x)
# TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE

import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345
",database="student")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()

# TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON INTERFACE


import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
if conn.is_connected()==False:
print("Error connecting to MYSQL DATABASE")
c=conn.cursor()
c.execute("select * from student where marks>90")
r=c.fetchall()
count=c.rowcount
print("total no of rows:",count)
for row in r:
print(row)
#TO INSERT A RECORD (ROLLNO,NAME,AND MARKS) IN MYSQL TABLE student USING
#PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student") mycursor=mydb.cursor()
r=int(input("enter the rollno"))
n=input("enter name")
m=int(input("enter marks"))
mycursor.execute("INSERT INTO student(rollno,name,marks)
VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD INSERTED")

# TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student") mycursor=mydb.cursor()
mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
mydb.commit()
print(mycursor.rowcount,"RECORD UPDATED")
# TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM STUDENT WHERE MARKS<50")
mydb.commit()
print(mycursor.rowcount,"RECORD DELETED")

# TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("DROP TABLE STUDENT")

# TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT ADD AGE INT”)
mydb.commit()

#TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE DROP AGE ”)
mydb.commit()

# TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
 commit( ): After executing insert or update query we must commit our
transaction using commit method of connection object.
Eg: mycon.commit()
 rollback( ): mysqlConnection.rollback() reverts the changes made by the
current transaction.
 rowcount: This attribute returns the number of rows that were affected
by an execute()

Closing cursor and connection


Since the database can keep limited number of connections at a time ,
we must close the connection using
cursorobject.close()
Eg: mycursor.close()
con.close()
Model Questions

I. Multiple choice Questions(MCQ):


1. DBMS stands for
a) Data Base Management Software
b) Data Base Maintenance System
c) Data Basic Management System
d) Data Base management system

2. In RDBMS, R stands for


a) Relational b)Rotational c)Rational d)None of the above

3. A Database contains one or more_ _


a) Data b)Tables c)Files d)Links

4. What is not true in respect of DBMS?


a) Database enforces standards
b) Database increases redundancy
c) Database facilitates sharing of data
d) Database helps to maintain integrity
5. Cardinality is total _
a) number of rows in a table
b) number of columns in a table
c) number of data items in a table
d) none of the above

6. Degree refers to total


a) number of rows in a table
b) number of columns in a table
c) number of data items in a table
d) none of the above

7. Referential Integrity is a rule that ensures between records in


related tables are valid.
a) Links b)difference c)relationship d)similarity

8. Data about data is


a) Data redundancy
b) Meta Data
c) Database schema
d) None of the above

9. Repetition of data is called ..............


a) Data redundancy
b) Data Description
c) Data inconsistency
d) None of the above

10. Mismatched redundant copies of data is known as data ............


a) Dependence b)Inconsistency c)Isolation d)Redundancy

11. A.............is an organized collection of structured data.


a) Database
b) File
c) DBMS
d) Information
12. A data..................is a set of rules that define valid data.
a) Query b)Constraint c)Dictionary d)All of the above

13. A relational database consists of a collection of ..............


a) Fields b)Records c)Keys d)Tables

14. A row in a database.


a) Field b)Record c)Key d)Table

15. The term is used to refer to a field in a table.


a) Attribute b)Row c)Tuple d)Instance

16. Which of the following statements is not true about relational database?
a) Relational data model is the most widely used data model.
b) The data is arranged as a collection of tables in relational database.
c) Relational database increases data redundancy and inconsistency.
d) None of the above.

17. Which of the following is a disadvantage of file processing system?


a) Data redundancy
b) Data isolation
c) Data inconsistency
d) All of the above

18. A _ is a property of the entire relation, rather than of the individual tuples in
which each tuple is unique.
a) Rows b)Key c)Attribute d)Fields

19. Which one of the following attribute can be taken as a primary key?
a) Name b)Street c)Id d)Department

20. A _ integrity constraint requires that the values appearing in specified


attributes of any tuple in the referencing relation also appear in specified
attributes of at least one tuple in the referenced relation.
a) Referencing b)Referential c)Primary d)Specific
21. Answer the questions based on the table Employee.
Table: Employee

EMPID ENAME SALARY DEPTNO Email


1001 George 30000 10 George23@yahoo.co.in
1002 Mary 32000 12 Mary_123@yahoo.co.in
1003 Alwin 25000 12 Al_win@gmail.com
1004 Sumit 20000 11 Sumit_222@yahoo.co.in

a) The cardinality of the table Employee is ……


i) 5 ii)4 iii)3 iv)6

b) The degree of the table Employee is …….


i) 3 ii)4 iii)5 iv)6

c) Which column can be made as the primary key in the table Employee?
i) EMPID
ii) EMAIL
iii) Both i and ii
iv) None of the above

d) If two columns are added to the table Employee, then the cardinality and
degree of the table is …… and …… respectively.
i) 4,7
ii) 7, 4
iii) 6,5
iv) 5,6

e) State True/False:
Both EMPID and EMAIL can be defined as primary key in the table
Employee.
i) True ii)False

22. An attribute in a relation is a foreign key if it is the _ key in any other


relation.
a) Candidate b)Primary c)Super d)Sub
23. A(n) in a table represents a logical relationship among a set of values.
a) Column b)Key c)Row d)Attribute

24. Which of the following attributes can be considered as a choice for the primary
key?
a) Name b)Street c)RollNo d)Subject

Fill in the blanks:

1) _ helps in efficient retrieval, inserting and deleting of data.


2) _ is a software for creating and managing databases.
3) means that data is accurate and consistent in the database.
4) - ensure that the database properly changes states upon a
successfully committed transaction.
5) RDBMS stands for .
6) In RDBMS a database is considered as a collection of
7) Collection of rows and columns are called as
8) Record is also called as a
9) The group of one or more columns used to uniquely identify each row of a relation
is called
10) is data about data.
11) A is a request to a database for obtaining information in a desired way.
12) _ is collection of values from which the value is derived for a column.
13) are the columns of a table that points to the primary key of another table.
Worksheet 1:
1. There is a column HOBBY in a Table CONTACTS. The following two statements are
giving different outputs. What may be the possible reason ?
a. SELECT COUNT(*) FROM CONTACTS;
b. SELECT COUNT(HOBBY)FROM CONTACTS;
2. Given the following employee table:-

a.What values will the following statements return ?


b.SELECT COUNT(*) FROM Employee;
b. SELECT COUNT(Commission) FROM Employee;
3..What will be the output of the following queries on the basis of Employee table:

a. Select avg(Salary) from Employee;


b. Select Salary+100 from Employee where EmpId='A002';

4. Kunal has entered the following SQL command on Table ‘STUDENT’ that has
TotalMarks as one of the columns.
SELECT COUNT (*) FROM STUDENT;
The output displayed is 20. Then, Kunal enters the following command :
SELECT COUNT (*) FROM STUDENT WHERE TotalMarks <100;
The output displayed is 15. Then, Kunal enters the following command :
SELECT COUNT (*) FROM STUDENT WHERE TotalMarks >= 100;
He predicts the output of the above query as 5. Do you agree with Kunal ? Give reason
for your answer.
5. Consider the table given below :
Write command for (i) and output for (ii)

i) To display Area along with number of Salespersons working in that area.

(ii) SELECT Area, COUNT (*) FROM Salesperson GROUP BY Area HAVING COUNT (*) > 1;

6. Consider the table ‘PERSONS’ given below. Write commands in SQL for (i) to (iv) and
write output for (i) to (iii)

(i) SELECT SUM(BasicSalary) FROM Persons Where Gender=’F’;


(ii) SELECT Gender,MIN(BasicSalary) FROM Persons GROUP BY gender;
(iii) SELECT Gender,Count(*) FROM Persons GROUP BY Gender;
7. In a database there are two tables 'Customer' and 'Bill' as shown below:

(i) How many rows and how many columns will be there in the Cartesian product of
these two tables?
(ii) Which column in the 'Bill' table is the foreign key?
8. Consider the tables HANDSETS and CUSTOMER given below:

With reference to these tables, Write commands in SQL for (i) and (ii) and output for (iii)
below:

(i) Display the CustNo, CustAddress and corresponding SetName for each customer.

(ii) Display the Customer Details for each customer who uses a Nokia handset.
(iii) select SetNo, SetName from Handsets, customer where SetNo = SetCode and
CustAddress = 'Delhi';
9. Consider the tables DOCTORS and PATIENTS given below:

With reference to these tables, write commands m SQL for (I) and (II) and output for (iii)
below:

(i) Display the PatNo, PatName and corresponding DocName for each patient
(ii) Display the list of all patients whose OPD_Days are MWF.
(iii) select OPD_Days, Count(*) from Doctors, Patients where Patients.Department
= Doctors.Department Group by OPD_Days;
Worksheet 2
1. The following table represents information on sales representatives of ABC company
with the following data.
Sales man name
Code
Address
commission
salary.
Write Python code to create the above table.

2. Write Python mysql connectivity program to retrieve all the data from a table student.

3. Write a python code to delete all the records from employee table whose age >60
and the table has the following fields. Empid, empname, deptid, age, payscale

4. Consider the information stored in the table : EMP

EMPNO ENAME DEPT SALARY


1 ALEX MUSIC 60000
2 PETER ART 67000
3 JOHNY WE 55000
4 RAMBO P&HE 48000

A python code is written to access the recordsof table: EMP, What will be the output
of following code:
# Assume All basic setup related to connection and cursorcreation is already done
query="select * from emp"
mycursor.execute(query)
results = mycursor.fetchone()
results = mycursor.fetchone()
results = mycursor.fetchone()
d = int (results[3])
print (d*3)

5. Consider the following Python code is written to access the details of employee,
whose employee number is passed to function:
Complete the missing statements:

def Search(eno):

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sy
stem",database="DB")
mycursor=mydb.cursor()
query="select * from emp where empno= ".format(eno)
mycursor.execute(query)
results = mycursor.
print(results)

6. Consider the following python code for updating the records.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="
system",database="student")
mycursor=mydb.cursor()
mycursor.execute("UPDATE STUDENT SET MARKS=95 WHERE MARKS=50")
print(mycursor.rowcount,"RECORD UPDATED")
Code is running but the record in actual database is not updating, what could be the
possible reason?

7. Which function of connection is used to check whether connection to


mysql is successfully done or not?
import mysql.connector as msq
con=msq.connect(#ConnectionString) # Assumingallparameterrequiredas
passed
if _:
print(“Connected!”)
else:
print(“ Error! Not Connected”)

8. What is the difference in fetchall() and fetchone()?

9. Write a python connectivity program to retrieve data, one record at a time from EMP
table for employees with id<10.

10. Write python connectivity program to delete the employee record whose name is
read from the keyboard at execution time.

11. SD School is managing the student data in student table in school database. Write a
python code that connects to database school and display the record of students and
total number of students.

12. Which record will get inserted in the table by the following code:
Import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="s
ystem",database="db")
mycursor=mydb.cursor()
a=1011
b=”Euphoria”
c=599.00
mycursor.execute("INSERT INTO BOOKS(bookid,bname,price) VALUES
({},'{}',{})" .format(a,b,c))
mydb.commit()
WORKSHEET 3 - Fill in the blanks

1.A-----------------is a special control structure that facilitates the row by row processing
of records in the resultset.
2.After importing mysqlconnector, first of all-------------is established by using connect()
3----------------method executes a database query from within Python.
4. Running of sql query through database cursor returns the table records in the form
of
5.A connectivity package-------------must be imported before running db connection
program.

WORKSHEET 4 -(Multiple Choice questions:)


1. Which of the following is not a legal method for fetching records from database.
a)fetchone() b)fetchtwo() c)fetchall() d)fetchmany()
2. To fetch one record from resultset you may use<curor>...........method.
a) fetch() b)fetchone() c)fetchtuple d)none of these.
3. To reflect the changes made in the database permanently you need to run……..
a) done() b)reflect() c)commit() d)final
4. To run an sql query from within python you may use cursor-------------method.
a) query() b)execute() c)commit() d)final()
5.A database..............controls the connection to an actual database , established in
program.
a) database object b)connection object c)fetch object d)query object

Very Short Answer Questions:


1. What is meant by a database?
A database is an organized collection of structured information, or inter-related data,
typically stored in a computer system.

2. What is primary key?


A primary key is a column or set of columns that contain values that uniquely identify
each row in a table.
3. What do you mean by candidate key?
It is an attribute or a set of attributes or keys participating for Primary Key, to uniquely
identify each record in that table.

4.What is meant by degree and cardinality of a table?


Degree refers to the number of attributes/columns in a relation. Cardinality refers to the
number of tuples/rows in a relation
5.What is meant by RDBMS?
RDBMS (relational database management system) is the software used to store, manage,
query, and retrieve data stored in a relational database. The RDBMS provides an
interface between users and applications and the database, as well as administrative
functions for managing data storage, access and performance.
6.What is meant by database schema?
Database schema is also called the visual or logical architecture as it tells us how the
data are organized in a database.

7.What is meant by data constraint?


Restrictions or limitations are put on the type of data that can be inserted in one or more
columns of a table to ensure accuracy and reliability of data in the database.
8.What is meant by relation?
A relation is a named, two dimensional table storing logically related data.

MODEL PRACTICE QUESTIONS:

1. Which command is used to add new column in existing table?


2. Which clause is used to search for NULL values in any column?
3. Which command is used to see information like name of columns, data type, size
4. Which clause is used for pattern matching? What are the 2 main characters used
for matching the pattern?
5. Which clause is used to see the output of query in ascending or descending order?

6. Which clause is used to eliminate the duplicate rows from output?


7. Which command is used to remove the table from database?
8. Which option of ORDER BY clause is used to arrange the output in descending
order?
9. Meetali is a database programmer, She has to write the query from EMPLOYEE
table to search for the employee who are getting any commission, for this she
has written the query as:
SELECT * FROM EMPLOYEE WHERE commission=null;
But the query is not producing the correct output, help Raj and correct the query
so that he gets the desired output.

10. Raj is a database programmer, He has to write the query from EMPLOYEE table to
search for the employee who are not getting any commission, for this he has
written the query as: SELECT * FROM EMPLOYEE WHERE commission=null;
But the query is not producing the correct output, help Raj and correct the query
so that he gets the desired output.

11. Deepika wants to remove all rows from the table BANK. But he needs to maintain
the structure of the table. Which command is used to implement the same?
12. While creating table ‘customer’, Rahul forgot to add column ‘price’. Which
command is used to add new column in the table. Write the command to
implement the same.

13. Observe the given Table TEACHER and give the output of question (i) and (ii)

TEACHER_CODE TEACHER_NAME DOJ

T001 ANAND 2001-01-30

T002 AMIT 2007-09-05

T003 ANKIT 2007-09-20

T004 BALBIR 2010-02-15

T005 JASBIR 2011-01-20

T006 KULBIR 2008-07-11


(i) SELECT TEACHER_NAME,DOJ FROM TEACHER WHERE TEACHER_NAME LIKE
“%I%”;
(ii) SELECT * FROM TEACHER WHERE DOJ LIKE “%-09-%”;

14. Write SQL QUERIES for q no 1 to 4

1. To display NO, NAME, TDATE from the table TRIP in descending order of NO.

2. To display the NAME of the drivers from the table TRIP who are traveling by transport
vehicle with code 101 or 103.

3. To display the NO and NAME of those drivers from the table TRIP who travelled
between ‘2015-02-10’ and ‘2015-04-01’.

4. To display all the details from table TRIP in which the distance travelled is more than
100 KM in ascending order of NOP
ANSWERS: 1. Multiple Choice Questions (MCQ )

1 D 2 A 3 B 4 B
5 A 6 B 7 C 8 B
9 A 10 B 11 A 12 B
13 D 14 B 15 A 16 C
17 D 18 B 19 C 20 B
21a) (ii) 21b) (iii) 21c) (iii) 21d) (ii)
21e) (ii) 22 B 23 C 24 C

Answers Fill in the blanks:

1 Database 2 DBMS 3 Data integrity


4 Consistency 5 Relational Database 6 Interrelated data
Management
System
7 Table 8 Tuple 9 Primary key
10 Meta – data 11 Query 1 Domain
2
13 Foreign key

ANSWER KEY WORKSHEET1 :


1. The column hobby may have NULL values, when we give count(colname) it
ignores null values while count(*) will count all duplicate and NULL values.
therefore two statements may give different values.
2. 3
1
3. I) 5300
II) NULL
4. Yes , as no of records =20 , students scoring <100 = 15. ; hence the students
scoring greater than equal to 100 will be 20-15 =5. As all the three statements
mentioned use count(*) as the count function.
5. i) select area,count(*) from salespersons group by area;
ii) North 2
South 2
6. I) 132000
II) F 42000
M 33000
III) F 3
M 4
7. i) 15 rows and 6 columns
ii) custID
8. i) select Custno,CustAddress,setName from customer c,handset h where
c.setNo=h.setName;
ii) select Custno,CustAddress,setName from customer c,handset h where
c.setNo=h.setName and h.setName like ‘Nokia%’;
iii) N2 Nokia 3G
B1 Blackberry
9. I) select patNo,PatName,DocName from Patient p,doctor d where
p.docID=d.docID;
II) select patNo,PatName,DocName from Patient p,doctor d where
p.docID=d.docID and OPD_Days=”MWF”;

ANSWER KEY FOR WORKSHEET2 :


1.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="sales") mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE SALESMAN (NAME VARCHAR(20),CODE INT
,ADDRESS VARCHAR(20), COMMISSION DEC,SALARY FLOAT);")
2.
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="DB") c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()
conn.close()

3.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="DB") mycursor=mydb.cursor()
mycursor.execute("DELETE FROM EMP WHERE AGE>60
") mydb.commit()
print(mycursor.rowcount,"RECORD DELETED")
mydb.close()

4. 165000

5. .{ } and fetchone()

6. con.commit() function is missing in the python code

7. con.is_connected()

8. fetchall() function is used to fetch all the records from the cursor in the form of tuple.
fetchone() isusedtofetchonerecordatatime. Subsequentfetchone() willfetch
nextrecords. If no more records to fetch, it returns None.
9. import mysql.connector

conn=mysql.connector.connect(host="localhost",user="root",passwd="system",datab
ase="com")
c=conn.cursor()
c.execute("select * from emp where id>10")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()
conn.close()
10.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="DB") mycursor=mydb.cursor()
s= input(“enter the name”)
mycursor.execute("delete from emp where name =’{}’)”.format(s)
mydb.commit()

11.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="school") mycursor=mydb.cursor()
sql=”select * from student”
mycursor.execute(sql)
recs=mycursor.fetchall()
count=0
for r in recs:
count+=1
print(r)
print(“total no of records”,count)

12. 1011 ,”Euphoria” 599.00

ANSWER KEY FOR WORKSHEET3 (Fill in the blanks)

1. database cursor
2. database connection.

3. execute()
4.resultset
5.mysql.connector

ANSWER KEY FOR WORKSHEET4 (MCQ)

1. b)fetchtwo()
2. b)fetchone()
3. c)commit()
4. b)execute()
5. b)connection object
Answers-MODEL PRACTICE QUESTIONS
1. ALTER TABLE
2. IS NULL
3. DESC
4. LIKE
% (percent) and _ (underscore)
5. ORDER BY

6. DISTINCT
7. DROP TABLE
8. DESC
9. SELECT * FROM EMPLOYEE WHERE commission IS NOT null;
10. SELECT * FROM EMPLOYEE WHERE commission IS null;
11. DELETE FROM BANK.

12. ALTER TABLE CUSTOMER ADD PRICE FLOAT;


13.
(i) TEACHER_NAME DOJ
-------------------------------------------------------
AMIT 2007-09-05
ANKIT 2007-09-20
BALBIR 2010-02-15
JASBIR 2011-01-20
KULBIR 2008-07-11

(ii)
TEACHER_CODE TEACHER_NAME DOJ
----------------------------------------------------------------------
T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20

14.
1. SELECT NO,NAME,TDATE FROM TRIP ORDER BY NO DESC;
2. SELECT NAME FROM TRIP WHERE TCODE=101 OR TCODE=103;
3. SELECT NO,NAME FROM TRIP WHERE TDATE BETWEEN ‘2015-02-10’ AND
‘2015-04-01’;
4. SELECT * FROM TRIP WHERE KM >100 ORDER BY NOP;

You might also like