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

Database Lab

The Lab Manual for MySQL provides a comprehensive guide for various experiments related to database management using MySQL, including installation, data manipulation, and integration with programming languages like Python and C. It covers essential topics such as creating schemas, tables, and executing queries, along with security measures for MySQL. The manual is structured with a clear table of contents and detailed instructions for each experiment, aimed at enhancing practical understanding of database concepts.

Uploaded by

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

Database Lab

The Lab Manual for MySQL provides a comprehensive guide for various experiments related to database management using MySQL, including installation, data manipulation, and integration with programming languages like Python and C. It covers essential topics such as creating schemas, tables, and executing queries, along with security measures for MySQL. The manual is structured with a clear table of contents and detailed instructions for each experiment, aimed at enhancing practical understanding of database concepts.

Uploaded by

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

Lab Manual for MySQL

Database Lab

Manik Chand Patnaik


Spring, 2019
Revised: 2022
Revised:2023
Table of Contents
Experiment 1 Installation of a DBMS Software 2
Experiment 2 MySQL Workbench (Frontend to DBMS) 4
Experiment 3 E-R and EER 17
Experiment 4 Data manipulation 25
Experiment 5 Select Queries 29
Experiment 6 Change and Delete Queries of DML 39
Experiment 7 Trigger, Procedure and Function 41
Experiment 8 Packages 50
Experiment 9 JDBC and Transactions 52
JDBC Driver, Connection, DDL in mysql / mariadb 52
Transactions with DML 54
Experiment 10 MySQL and C 56
Experiment 11 Database and Python 63
Create dataframe 63
Select and Project operation 63
Selecting in Options dataframe 63
Displaying the result 64
Perform Statistics on the data 64
Conclusion 66

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 1


Experiment 1 Installation of a
DBMS Software
MySQL Installation

We need the following items for running MySQL


server with GUI tools:-

1. Open Synaptic

2. Select MySQL Server


3. Select MySQL Workbench
4. Apply, it will install MySQL Server, Client alongwith the requisites.
5. During install configure the password for root user as “manager”. It is presumed that
you are using root/manager, scott/tiger and user/pass username and password
combinations.
6. Additionally those familiar with phpmyadmin may select it there, then it will install php,
php mysql along with other requisites.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 2


If your MySQL got corrupted

We can reinstall but we need to purge first.

$> sudo apt-get --purge remove mysql-server mysql-common mysql-client

MySQL Security / Lost Password

Setting Password for the root user : Did you see an error like this ?

ERROR 1045: Access denied for user: 'root@localhost' (Using password: YES/NO)

1. Stop the mysql demon process using this command : sudo /etc/init.d/mysql stop
2. Start the mysqld demon process using the --skip-grant-tables option with this
command sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
3. start the mysql client process using this command mysql -u root
4. from the mysql prompt execute this command to be able to change any password
FLUSH PRIVILEGES;
5. Then reset/update your password SET PASSWORD FOR root@'localhost' =
PASSWORD('manager');
6. FLUSH PRIVILEGES;
7. $> sudo /etc/init.d/mysql stop
8. $> sudo /etc/init.d/mysql start

Alternate Method:
USE mysql
UPDATE user SET Password = PASSWORD('newpwd')
WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:
USE mysql
UPDATE user SET Password = PASSWORD('newpwd')
WHERE Host = '%' AND User = 'root';

MySQL Security can be hardened using $> sudo mysql_secure_installation


1. Update the password plugin (Press Y for yes and hit the Enter key on your keyboard)
2. Select the level of password validation policy you want to enable (0 = low, 1 = medium,
2 = strong). Important note: Later in this article I offer cautionary details about this
policy level.
3. Change the root password (to dismiss this option, type N, so the tool does not change
the admin password for MySQL)
4. Remove anonymous users (Press Y to remove)
5. Disallow remote root login (Press Y to disable)
6. Remove test database (Press Y to remove)

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 3


Experiment 2 MySQL Workbench (Frontend to DBMS)

Now Login to root and create database for the lab

Then we create a user to use the database

Select User and Privileges

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 4


Add Account

Type a password here the password is pass

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 5


It is a weak password still we are using it for learning sake.

Then select Schema privileges

Then add entry

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 6


Select the created database

Then press OK.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 7


Then select all to provide all rights to the user on project database

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 8


Press Apply

Add a connection for the user

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 9


Test the connection by providing the password

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 10


Now press OK to save.

Open the connection by clicking on it.

Provide the password so that the SQL Editor opens.

Here we have a tab named Query 1.

In this tab we will type query to create tables.

The MySQL Query for creation of the tables are as follows:-

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 11


SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `project` DEFAULT CHARACTER SET utf8 COLLATE
utf8_unicode_ci ;
USE `project` ;

-- -----------------------------------------------------
-- Table `project`.`client_master`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project`.`client_master` (
`client_no` INT NOT NULL,
`name` VARCHAR(45) NULL,
`city` VARCHAR(20) NULL,
`pincode` VARCHAR(6) NULL,
`state` VARCHAR(20) NULL,
`bal_due` INT NULL,
PRIMARY KEY (`client_no`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `project`.`product_master`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project`.`product_master` (
`product_no` VARCHAR(6) NOT NULL,
`description` VARCHAR(45) NULL,
`profit` DECIMAL(5,2) NULL,
`unit_percent` VARCHAR(20) NULL,
`quantity_measured` INT NULL,
`reorder_on_hand` INT NULL,
`sell_price` INT NULL,
`cost_price` INT NULL,
PRIMARY KEY (`product_no`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `project`.`salesman_master`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project`.`salesman_master` (
`salesman_no` INT NOT NULL,
`salesman_name` VARCHAR(45) NULL,
`address` VARCHAR(45) NULL,
`city` VARCHAR(20) NULL,
`pincode` VARCHAR(6) NULL,
`state` VARCHAR(20) NULL,
`salamt` INT NULL,
`tgt_to_get` INT NULL,

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 12


`ytd` INT NULL,
`remarks` VARCHAR(45) NULL,
PRIMARY KEY (`salesman_no`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `project`.`sales_order`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project`.`sales_order` (
`s_orderno` INT NOT NULL,
`s_orderdate` DATE NULL,
`client_no` INT NULL,
`dely` CHAR(1) NULL,
`bill` CHAR(1) NULL,
`salesman_no` INT NULL,
`delay` DATE NULL,
`orderstatus` VARCHAR(10) NULL,
PRIMARY KEY (`s_orderno`),
INDEX `fk_sales_order_1_idx` (`salesman_no` ASC),
INDEX `fk_sales_order_2_idx` (`client_no` ASC),
CONSTRAINT `fk_sales_order_1`
FOREIGN KEY (`salesman_no`)
REFERENCES `project`.`salesman_master` (`salesman_no`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_sales_order_2`
FOREIGN KEY (`client_no`)
REFERENCES `project`.`client_master` (`client_no`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `project`.`sales_order_details`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project`.`sales_order_details` (
`s_orderno` INT NULL,
`product_no` VARCHAR(6) NULL,
`qty_ordered` INT NULL,
`qty_disp` INT NULL,
`product_rate` INT NULL,
INDEX `fk_sales_order_details_1_idx` (`s_orderno` ASC),
INDEX `fk_sales_order_details_2_idx` (`product_no` ASC),
CONSTRAINT `fk_sales_order_details_1`
FOREIGN KEY (`s_orderno`)
REFERENCES `project`.`sales_order` (`s_orderno`)
ON DELETE CASCADE
ON UPDATE CASCADE,

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 13


CONSTRAINT `fk_sales_order_details_2`
FOREIGN KEY (`product_no`)
REFERENCES `project`.`product_master` (`product_no`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

Forward Engineering is success.


Let’s see the output of describe <tablename>
mysql> use project;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+---------------------+
| Tables_in_project |
+---------------------+
| client_master |
| product_master |
| sales_order |
| sales_order_details |
| salesman_master |
+---------------------+
5 rows in set (0.00 sec)

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 14


mysql> describe client_master;
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| client_no | int(11) | NO | PRI | NULL | |
| name | varchar(45) | YES | | NULL | |
| city | varchar(20) | YES | | NULL | |
| pincode | varchar(6) | YES | | NULL | |
| state | varchar(20) | YES | | NULL | |
| bal_due | int(11) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> desc product_master;


+-------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| product_no | varchar(6) | NO | PRI | NULL | |
| description | varchar(45) | YES | | NULL | |
| profit | decimal(5,2) | YES | | NULL | |
| unit_percent | varchar(20) | YES | | NULL | |
| quantity_measured | int(11) | YES | | NULL | |
| reorder_on_hand | int(11) | YES | | NULL | |
| sell_price | int(11) | YES | | NULL | |
| cost_price | int(11) | YES | | NULL | |
+-------------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> desc sales_order;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| s_orderno | int(11) | NO | PRI | NULL | |
| s_orderdate | date | YES | | NULL| |
| client_no | int(11) | YES | MUL | NULL | |
| dely | char(1) | YES | | NULL| |
| bill | char(1) | YES | | NULL| |
| salesman_no | int(11) | YES | MUL | NULL | |
| delay | date | YES | | NULL| |
| orderstatus | varchar(10) | YES | | NULL| |
+-------------+-------------+------+-----+---------+-------+
8 rows in set (0.01 sec)

mysql> desc sales_order_details;


+--------------+------------+------+-----+---------+-------+

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 15


| Field | Type | Null | Key | Default | Extra |
+--------------+------------+------+-----+---------+-------+
| s_orderno | int(11) | YES | MUL | NULL | |
| product_no | varchar(6) | YES | MUL | NULL | |
| qty_ordered | int(11)| YES | | NULL| |
| qty_disp | int(11) | YES | | NULL| |
| product_rate | int(11)| YES | | NULL| |
+--------------+------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> desc salesman_master;


+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| salesman_no | int(11) | NO | PRI | NULL | |
| salesman_name | varchar(45) | YES | | NULL| |
| address | varchar(45) | YES | | NULL| |
| city | varchar(20) | YES | | NULL| |
| pincode | varchar(6) | YES | | NULL| |
| state | varchar(20) | YES | | NULL| |
| salamt | int(11) | YES | | NULL| |
| tgt_to_get| int(11) | YES | | NULL| |
| ytd | int(11) | YES | | NULL| |
| remarks | varchar(45) | YES | | NULL| |
+---------------+-------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 16


Experiment 3 E-R and EER
Let’s create the E-R diagram of the exemplary database empinfo. Then we will create the
implementation.

Select File -> New Model

Let’s change the default name mydb to empinfo. Right click mydb and select to edit schema

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 17


Rename to empinfo and select utf8_unicode_ci collation.

Now save as mwb file.

Add the EER diagram

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 18


In the diagram view select the button for table

Place on the blank space and right click on the table to edit.

Create the tables and add foreign key constraint as the following picture shows

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 19


We can give cascade for key values.

Final view

Let’s forward engineer the database.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 20


In the dialog there are some options. Keep them as it was. There is no need to change.

In the next dialog

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 21


Just press next. There is no need to select anything.

The SQL is shown.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 22


Success message is shown. Now we can close.

Let’s run the following command to see if the foreign keys are actually created or not.

Presentin table is also created. See ...

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 23


Manik Chand Patnaik, https://www.manik.in/StudSupp/ 24
Experiment 4 Data manipulation
Let’s use the previously created schema

This is the EER diagram of the tables.

Insert values for tables


INSERT INTO `project`.`client_master`
VALUES(0001,'Ivan','Bombay','400054','Maharastra',15000);
INSERT INTO `project`.`client_master`
VALUES(0002,'Vandana','Madras','780001','Tamilnadu',0);
INSERT INTO `project`.`client_master`
VALUES(0003,'Pramada','Bombay','400057','Maharastra',5000);
INSERT INTO `project`.`client_master`
VALUES(0004,'Basu','Bombay','400056','Maharastra',0);

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 25


INSERT INTO `project`.`client_master`
VALUES(0005,'Ravi','Delhi','100001','',2000);
INSERT INTO `project`.`client_master`
VALUES(0006,'Rukmani','Bombay','400050','Maharastra',0);

INSERT INTO `project`.`product_master` VALUES ('P00001','1.44


Floppies',5,'Piece',100,20,525,500);
INSERT INTO `project`.`product_master` VALUES
('P03453','Monitors',6,'Piece',10,3,12000,11200);
INSERT INTO `project`.`product_master` VALUES
('P06734','Mouse',5,'Piece',20,5,1050,500);
INSERT INTO `project`.`product_master` VALUES ('P07865','1.2
Floppies',5,'Piece',100,20,525,500);
INSERT INTO `project`.`product_master` VALUES
('P07868','Keyboards',2,'Piece',10,3,3150,3050);
INSERT INTO `project`.`product_master` VALUES ('P07885','CD
Drive',2.5,'Piece',10,3,5250,5100);
INSERT INTO `project`.`product_master` VALUES ('P07965','540
HDD',4,'Piece',10,3,8400,8000);
INSERT INTO `project`.`product_master` VALUES ('P07975','1.44
Drive',5,'Piece',10,3,1050,1000);
INSERT INTO `project`.`product_master` VALUES ('P08865','1.2
Drive',5,'Piece',2,3,1050,1000);

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 26


INSERT INTO `project`.`salesman_master` VALUES (500001,'Kiran','A/14
Worli','Bombay','400002','Maharastra',3000,100,50,'Good');
INSERT INTO `project`.`salesman_master` VALUES (500002,'Manish','65,
Nariman','Bombay','400001','Maharastra',3000,200,100,'Good');
INSERT INTO `project`.`salesman_master` VALUES (500003,'Ravi','P-7
Bandra','Bombay','400032','Maharastra',3000,200,100,'Good');
INSERT INTO `project`.`salesman_master` VALUES (500004,'Ashish','A/5
Juhu','Bombay','400044','Maharastra',3500,200,150,'Good');

INSERT INTO `project`.`sales_order` VALUES


(019001,'1996-01-12',0001,'F','N',500001,'1996-01-20','Ip');
INSERT INTO `project`.`sales_order` VALUES
(019002,'1996-01-25',0002,'P','N',500002,'1996-01-27','C');
INSERT INTO `project`.`sales_order` VALUES
(016865,'1996-02-18',0003,'F','Y',500003,'1996-02-20','F');
INSERT INTO `project`.`sales_order` VALUES
(019003,'1996-04-03',0001,'F','Y',500004,'1996-04-07','F');
INSERT INTO `project`.`sales_order` VALUES
(046866,'1996-05-20',0004,'P','N',500002,'1996-05-22','C');
INSERT INTO `project`.`sales_order` VALUES
(010008,'1996-05-24',0005,'F','N',500004,'1996-05-26','Ips');

use project;
INSERT INTO `sales_order_details` VALUES
(19001,'P00001',4,4,525),(19001,'P07965',2,1,8400),
(19001,'P07885',2,1,5250),(19002,'P00001',10,0,525),
(19003,'P00001',4,4,1050),(19003,'P03453',2,2,1050),
(46866,'P06734',1,1,12000),(46866,'P07965',1,0,8400),
(10008,'P07975',1,0,1050),(10008,'P00001',10,5,525);

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 27


Manik Chand Patnaik, https://www.manik.in/StudSupp/ 28
Experiment 5 Select Queries
Queries comprise of either Projection, Selection or both. Projection is selecting specific
columns to view. Like the following examples

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 29


Selection in Query represents selecting specific rows based on some condition. Both
Projection and selection can be combined in a query. See the following examples.

This is where clause when we select depending on whether the row has a value
corresponding to the search phrase (Bombay). We use = in the where clause.

When the search phrase has more than one value we use in predicate of the where clause.
The parenthesis may contain one or more values.

When we need to satisfy either of two conditions, we use or in where clause. This is similar to
and where both must satisfy.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 30


When we don’t know the exact value but know about a condition where the value has to be
greater than or less than, then we can use > or < symbol.

When we search for rows which do not meet a criteria we use the criteria with a not modifier.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 31


Aggregate Functions in SQL (Create emp table first)

https://docs.google.com/document/d/16p5AzWYvK748nWq-cJr5lltvbUZYJoszQ8ffJAbC7aA/ed
it?usp=sharing
mysql> select * from emp;
+-----+------------+-------+------------+
| eid | ename | sal | dept |
+-----+------------+-------+------------+
| 1 | Harry | 10000 | Marketing |
| 2 | Sejal | 9500 | Marketing |
| 3 | Raman | 10500 | Marketing |
| 4 | Daman | 9900 | Marketing |
| 5 | Chalapathi | 7500 | Finance |
| 6 | Raghav | 8000 | Finance |
| 7 | Neha | 7500 | Office |
| 8 | Sobha | 8000 | Office |
| 9 | Harpreet | 8500 | Production |
| 10 | Meghna | 9700 | Production |
| 11 | Sekhar | 10000 | HR |
| 12 | Shikha | 10000 | HR |
| 13 | Sobhan | 8700 | Support |
| 14 | Indu | 9900 | Support |
| 15 | Nakul | 7050 | Support |
+-----+------------+-------+------------+
15 rows in set (0.01 sec)

AVG – calculates the average of a set of values.

Q: Find average salary in a department

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 32


COUNT – counts rows in a specified table or view.

Q: Find count of employees in each department

MIN – gets the minimum value in a set of values.

Q: Find minimum salary in each department

MAX – gets the maximum value in a set of values.

Q: Find maximum salary in each department

SUM – calculates the sum of values.

Q: Find total salary disbursed in each department

DISTINCT - Remove duplicates

Q: Show only departments in the emp table.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 33


Join multiple tables

Customer table

Insert Data
insert into customer values(1,'Harry','Marketing');
insert into customer values(5,'Chalapathy','Finance');
insert into customer values(6, 'Raghav','Finance');
insert into customer values(7, 'Neha','Office');
insert into customer values(12,'Shikha','HR');
insert into customer values(13,'Sobhan','Support');

Saleorder table

Insert data
insert into saleorder values(1,1200,1);
insert into saleorder values(2,1050,1);
insert into saleorder values(3,1200,5);
insert into saleorder values(4,100,6);
insert into saleorder values(5,200,13);

Joined output

INNER JOIN

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 34


OUTER JOIN

Left Outer Join

Right Outer Join

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 35


Full Outer Join is simulated as a UNION

SELF JOIN

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 36


INTERSECTION
SELECT * FROM emp where sal < 9000
intersect
SELECT * FROM Customer where sal > 10000;

SubQuery

Query inside another query is subquery. It is used to get information which is dependent on
another query’s output

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 37


Manik Chand Patnaik, https://www.manik.in/StudSupp/ 38
Experiment 6 Change and Delete Queries of DML
Change the value of the order with orderid as 1 to 1500
mysql> select * from saleorder ;
+---------+-------+------------+
| orderid | value | customerid |
+---------+-------+------------+
| 1 | 1200 | 1 |
| 2 | 1050 | 1 |
| 3 | 1200 | 5 |
| 4 | 100 | 6 |
| 5 | 200 | 13 |
+---------+-------+------------+
5 rows in set (0.01 sec)

mysql> update saleorder set value=1500 where orderid=1;


Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from saleorder;


+---------+-------+------------+
| orderid | value | customerid |
+---------+-------+------------+
| 1 | 1500 | 1 |
| 2 | 1050 | 1 |
| 3 | 1200 | 5 |
| 4 | 100 | 6 |
| 5 | 200 | 13 |
+---------+-------+------------+
5 rows in set (0.00 sec)

Delete the record with orderid=5 from the saleorder table

mysql> delete from saleorder where orderid=5;


Query OK, 1 row affected (0.01 sec)

Change Nakul to Pravat in emp table.

mysql> update emp set ename='Pravat' where ename='Nakul';


Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 39


Change the salary of Pravat to 7500
mysql> update emp set sal=7500 where ename='Pravat';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Find salary of Pravat and add 50 to it.


mysql> update emp set sal=sal+50 where ename='Pravat';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 40


Experiment 7 Trigger, Procedure and Function
Let’s see an insert query and how that can be checked for bad data and corrected by a
trigger.

Step1 Schema mysql> create schema student;

Step2 Create user and assign Privileges

Step3 Create connection

Create table for our work

Now the table is created. See the desc

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 41


Trigger : Now let’s create the trigger and execute it.

Check whether it is really created or not

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 42


Now it is time to insert data and see if our trigger responds.

Let’s see the data which got actually inserted.

Let’s also analyze the outputs here: desc returned 4 rows, insert affected 1 row and select
returned 1 row. Create table and Create trigger did not affect rows, as well as Create schema.

The input -10 was corrected by the trigger to value zero here.

Procedure : Let’s create a procedure to count the number of students in the table.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 43


Now check whether it is created or not.

Now we will call it in SQL

“ ”
A Primer for variables in MySQL

Do you remember your semester DBMS SQL class? Anything looks similar?
May not be. What is this @ symbol you might be wondering. I have given a
refman link here. You may click it.

MySQL has the concept of user-defined variables. They are loosely typed variables that may
be initialized somewhere in a session and keep their value until the session ends. They are
prepended with an @ sign, like this: @var. You can initialize this variable with a SET statement
or inside in a query:

SET @var = 1
SELECT @var2 := 2

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 44


The symbol := is the bind symbol

When you write a stored procedure in MySQL, you can pass the input parameters and declare
the local variables:

These variables are not prepended with any prefixes.

The difference between a procedure variable and a session-specific user-defined variable is


that procedure variable is re-initialized to NULL each time the procedure is called, while the
session-specific variable is not:

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 45


As you can see, var2 (procedure variable) is re-initialized each time the procedure is called,
while @var2 (session-specific variable) is not.

(In addition to user-defined variables, MySQL also has some predefined "system variables",
which may be "global variables" such as @@global.port or "session variables" such as
@@session.sql_mode; these "session variables" are unrelated to session-specific user-defined
variables.)

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 46


Function :

A function in MySQL can be used inside SQL query unlike procedure. So we can pass a
column name to generate a list like this.

Procedure vs Functions in MySQL

The most general difference between procedures and functions is that they are invoked
differently and for different purposes:

1. A procedure does not return a value. Instead, it is invoked with a CALL statement to
perform an operation such as modifying a table or processing retrieved records.
2. A function is invoked within an expression and returns a single value directly to the
caller to be used in the expression.
3. You cannot invoke a function with a CALL statement, nor can you invoke a procedure
in an expression.

Syntax for routine creation differs for procedures and functions:

1. Procedure parameters can be defined as IN, OUT, or INOUT. This means that a
procedure can pass values back to the caller by using output parameters. These

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 47


values can be accessed in statements that follow the CALL statement. Functions have
only input parameters. As a result, although both procedures and functions can have
parameters, procedure parameter declaration differs from that for functions.
2. Functions return value, so there must be a RETURNS clause in a function definition to
indicate the data type of the return value. Also, there must be at least one RETURN
statement within the function body to return a value to the caller. RETURNS and
RETURN do not appear in procedure definitions.
○ To invoke a stored procedure, use the CALL statement. To invoke a stored
function, use it in an expression. The function returns a value during
expression evaluation.
○ A procedure is invoked using a CALL statement, and can only pass back
values using output variables. A function can be called from inside a statement
just like any other function (that is, by invoking the function's name), and can
return a scalar value.
○ Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE.
For a FUNCTION, parameters are always regarded as IN parameters.
3. If no keyword is given before a parameter name, it is an IN parameter by default.
Parameters for stored functions are not preceded by IN, OUT, or INOUT. All function
parameters are treated as IN parameters.
4. Stored procedures are compiled so are very fast. Functions are not compiled. They
are parsed and executed at run-time.
5. Functions Cannot affect the state of database (Statements that do commit or rollback
are disallowed in function) Whereas Stored procedures Can affect the state of
database using commit.

Cursor

Database cursor is used to loop through data extracted in stored procedures.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 48


Manik Chand Patnaik, https://www.manik.in/StudSupp/ 49
Experiment 8 Packages
The CREATE PACKAGE BODY statement can be used when Oracle SQL_MODE is set.
Oracle-style packages were introduced in MariaDB 10.3.5. The current version of MariaDB is: -

The CREATE PACKAGE BODY statement creates the package body for a stored package. The
package specification must be previously created using the CREATE PACKAGE statement.

A package body provides implementations of the package public routines and can optionally
have:

● package-wide private variables


● package private routines
● forward declarations for private routines
● an executable initialization section

SET sql_mode=ORACLE;
DELIMITER $$
CREATE OR REPLACE PACKAGE employee_tools AS
FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2);
PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2));
PROCEDURE raiseSalaryStd(eid INT);
PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2));
END;
$$
CREATE PACKAGE BODY employee_tools AS
-- package body variables
stdRaiseAmount DECIMAL(10,2):=500;

-- private routines
PROCEDURE log (eid INT, ecmnt TEXT) AS
BEGIN
INSERT INTO employee_log (id, cmnt) VALUES (eid, ecmnt);
END;

-- public routines
PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2)) AS
eid INT;
BEGIN
INSERT INTO employee (name, salary) VALUES (ename, esalary);

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 50


eid:= last_insert_id();
log(eid, 'hire ' || ename);
END;

FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2) AS


nSalary DECIMAL(10,2);
BEGIN
SELECT salary INTO nSalary FROM employee WHERE id=eid;
log(eid, 'getSalary id=' || eid || ' salary=' || nSalary);
RETURN nSalary;
END;

PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2)) AS


BEGIN
UPDATE employee SET salary=salary+amount WHERE id=eid;
log(eid, 'raiseSalary id=' || eid || ' amount=' || amount);
END;

PROCEDURE raiseSalaryStd(eid INT) AS


BEGIN
raiseSalary(eid, stdRaiseAmount);
log(eid, 'raiseSalaryStd id=' || eid);
END;

BEGIN
-- This code is executed when the current session
-- accesses any of the package routines for the first time
log(0, 'Session ' || connection_id() || ' ' || current_user || '
started');
END;
$$

DELIMITER ;

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 51


Experiment 9 JDBC and Transactions
JDBC Driver, Connection, DDL in mysql / mariadb
The Jar should be visible in project explorer for the project to compile and run.

package Hello;
import java.sql.*;
public class Main {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
static final String DB_URL =
"jdbc:mariadb://localhost/student";
// Database credentials
static final String USER = "scott";
static final String PASS = "tiger";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("org.mariadb.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");

//STEP 4: Execute a query


System.out.println("Creating table in given database...");
stmt = conn.createStatement();

String sql = "CREATE TABLE IF NOT EXISTS studinfo "


+ "(sid int not null primary key, "
+ " name VARCHAR(25), "
+ " std int);";

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 52


stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
//finally block is optional
finally {
//finally block used to close resources
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}// do nothing
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}

}
OUTPUT

Created table

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 53


Transactions with DML
/**
* @author manik
*/
import java.sql.*;

public class TransDemo {

public static void main(String[] args) {


try {
Class.forName("com.mysql.jdbc.Driver");//driver
String url =
"jdbc:mysql://localhost:3306/Student?zeroDateTimeBehavior=convertToNull"
;
//database specific url ^server ^hostname ^port ^db ^for date type
String user = "scott";
String password = "tiger";
Connection con = DriverManager.getConnection(url, user,
password);
Statement st = con.createStatement();
st.execute("delete from emp");
con.setAutoCommit(false); //setting commit of each statement
to false
String in = "insert into emp values(?,?,?,?)";
PreparedStatement stmt = con.prepareStatement(in);
//Set values in format. You can use a loop for many records
stmt.setInt(1, 11);
stmt.setString(2, "Rajdeep");
stmt.setInt(3, 15000);
stmt.setInt(4, 3);
//run the statement
Savepoint savepoint1 = con.setSavepoint("Savepoint1");

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 54


int output = stmt.executeUpdate();
//Set values in format. You can use a loop for many records
stmt.setInt(1, 12);
stmt.setString(2, "Rajesh");
stmt.setInt(3, 13000);
stmt.setInt(4, 3);
//run the statement
output = output + stmt.executeUpdate();
Statement stmt2 = con.createStatement();
Savepoint savepoint2 = con.setSavepoint("Savepoint2");
stmt2.executeUpdate("Delete from emp");
//we want to rollback to get back our data
con.rollback(savepoint2);
con.commit(); //this commits all previous savepoints -> we
cant rollback
if (output > 0) {
System.out.println("Rows Affected : " + output);
}
//select sql query
String sql = "select * from emp";
ResultSet res = stmt.executeQuery(sql);
//loop to extract data
while (res.next()) {
int eno = res.getInt("eno");
String ename = res.getString("ename");
int sal = res.getInt("sal");
int level = res.getInt("level");
System.out.println("data :" + eno + "\t" + ename + "\t"
+ sal + "\t" + level);
}
//close resources used
res.close();
stmt.close();
stmt2.close();
con.close();
} //error handling
catch (ClassNotFoundException ex) {
System.out.println("Class not found " + ex.getMessage());
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 55


Experiment 10 MySQL and C
Open Synaptic and install libmysqlclient-dev.

It will mark several other supporting libraries

Open a test programming file to check version of mysql client

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 56


Without Library installation programs won’t compile

With correct libraries the program will compile and run well.

Output

Create a table

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 57


The tablecreate.c file is here
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>

void finish_with_error(MYSQL *con) {


fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}

int main(int argc, char **argv) {


MYSQL *con = mysql_init(NULL);

if (con == NULL) {
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}

if (mysql_real_connect(con, "localhost", "scott", "tiger",


"student", 0, NULL, 0) == NULL) {
finish_with_error(con);
}

if (mysql_query(con, "DROP TABLE IF EXISTS cars")) {


finish_with_error(con);
}

if (mysql_query(con, "CREATE TABLE cars(id INT PRIMARY KEY


AUTO_INCREMENT, name VARCHAR(255), price INT)")) {
finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(1,'Audi',52642)")) {


finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(2,'Mercedes',57127)")) {


finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(3,'Skoda',9000)")) {


finish_with_error(con);
}

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 58


if (mysql_query(con, "INSERT INTO cars VALUES(4,'Volvo',29000)")) {
finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(5,'Bentley',350000)")) {


finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(6,'Citroen',21000)")) {


finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(7,'Hummer',41400)")) {


finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO cars VALUES(8,'Volkswagen',21600)"))


{
finish_with_error(con);
}

mysql_close(con);
exit(0);
}

Program when run won’t show any output. Verify it from command line

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 59


Select query
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>

void finish_with_error(MYSQL *con) {


fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}

int main(int argc, char **argv)


{
MYSQL *con = mysql_init(NULL);

if (con == NULL) {
fprintf(stderr, "mysql_init() failed\n");
exit(1);
}

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 60


if (mysql_real_connect(con, "localhost", "scott", "tiger",
"student", 0, NULL, 0) == NULL) {
finish_with_error(con);
}

if (mysql_query(con, "SELECT * FROM cars")) {


finish_with_error(con);
}

MYSQL_RES *result = mysql_store_result(con);

if (result == NULL) {
finish_with_error(con);
}

int num_fields = mysql_num_fields(result);

MYSQL_ROW row;

while ((row = mysql_fetch_row(result))) {


for(int i = 0; i < num_fields; i++) {
printf("%s ", row[i] ? row[i] : "NULL");
}

printf("\n");
}

mysql_free_result(result);
mysql_close(con);

exit(0);
}

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 61


Manik Chand Patnaik, https://www.manik.in/StudSupp/ 62
Experiment 11 Database and Python
In python we use Pandas for handling tabular data. In this experiment we will handle pandas
dataframe to manipulate data. The iPython outputs are indicated by Out[x]:

Create dataframe
import pandas as pd
df = pd.DataFrame(
{
"eid": [1,2,3,4,5,6],
"ename": ["Harry","Sejal","Raman",
"Daman","Chalapathi","Raghav"],
"sal": [10000,9500,10500,9900,7500,8000],
"dept": ["Marketing","Marketing","Finance",
"Office","Production","HR"]
}
)

Select and Project operation


1. Find rows where the salary is greater than 9000.
2. Find rows where department is Marketing
3. Show only columns eid and ename
4. Show only columns ename and dept
select1 = df[df['sal'] > 9000]
select2 = df[df['dept'] == 'Marketing']
project1 = df[['eid','ename']]
project2 = df[['ename','dept']]

Selecting in Options dataframe


selectdept = ['Marketing', 'HR']

df.loc[df['dept'].isin(selectdept)]
Out[1]:
eid ename sal dept
0 1 Harry 10000 Marketing
1 2 Sejal 9500 Marketing
5 6 Raghav 8000 HR

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 63


Displaying the result
print("\nselect1\n",select1)
print("\nselect2\n",select2)
print("\nproject1\n",project1)
print("\nproject2\n",project2)

OUTPUT
select1
eid ename sal dept
0 1 Harry 10000 Marketing
1 2 Sejal 9500 Marketing
2 3 Raman 10500 Finance
3 4 Daman 9900 Office

select2
eid ename sal dept
0 1 Harry 10000 Marketing
1 2 Sejal 9500 Marketing

project1
eid ename
0 1 Harry
1 2 Sejal
2 3 Raman
3 4 Daman
4 5 Chalapathi
5 6 Raghav

project2
ename dept
0 Harry Marketing
1 Sejal Marketing
2 Raman Finance
3 Daman Office
4 Chalapathi Production
5 Raghav HR

Perform Statistics on the data


Properties of the dataframe

The x and y axes of the dataframe


df.axes
Out[1]:
[RangeIndex(start=0, stop=6, step=1),
Index(['eid', 'ename', 'sal', 'dept'], dtype='object')]

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 64


#The Rows and Columns of the dataframe
df.shape
Out[2]: (6, 4)

#Used datatypes in the dataframe


df.dtypes
Out[3]:
eid int64
ename object
sal int64
dept object
dtype: object

#Number of data items in the dataframe


df.size
Out[4]: 24

#The dimensions of the dataframe


df.ndim
Out[7]: 2

#Transpose (Row become columns and Columns become rows)


df.T
Out[8]:
0 1 2 3 4 5
eid 1 2 3 4 5 6
ename Harry Sejal Raman Daman Chalapathi Raghav
sal 10000 9500 10500 9900 7500 8000
dept Marketing Marketing Finance Office Production HR

#Create JSON from the dataframe


df.to_json(orient="split")
Out[9]:
'{"columns":["eid","ename","sal","dept"],"index":[0,1,2,3,4,5],"data":[[1,
"Harry",10000,"Marketing"],[2,"Sejal",9500,"Marketing"],[3,"Raman",10500,"
Finance"],[4,"Daman",9900,"Office"],[5,"Chalapathi",7500,"Production"],[6,
"Raghav",8000,"HR"]]}'

#Create csv file from dataframe


df.to_csv('file1.csv')

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 65


Find the Mean, Median, Standard Deviation, Minimum and Maximum
df['sal'].mean()
Out[1]: 9233.333333333334

df['sal'].median()
Out[2]: 9700.0

df['sal'].std()
Out[3]: 1202.7745701779143

df['sal'].min()
Out[4]: 7500

df['sal'].max()
Out[5]: 10500

Python and MySQL

Database Creation
#use the mysql driver
import mysql.connector

#connect to the database server


mydb = mysql.connector.connect(
host="localhost",
user="scott",
password="tiger"
)
#create a directional database pointer (Cursor)
mycursor = mydb.cursor()

#run query to create the database


mycursor.execute("CREATE DATABASE project")

#verify if the database is created


mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 66


Connecting to database and running sql
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="scott",
password="tiger",
database="project"
)
mycursor = mydb.cursor()

#run any sql query


mycursor.execute(" --- Write the sql query --- ")

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 67


Conclusion
Practice is the key to success.

Manik Chand Patnaik, https://www.manik.in/StudSupp/ 68

You might also like