Database Lab
Database Lab
Database Lab
1. Open Synaptic
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';
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,
-- -----------------------------------------------------
-- 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,
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
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)
Let’s change the default name mydb to empinfo. Right click mydb and select to edit schema
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
Final view
Let’s run the following command to see if the foreign keys are actually created or not.
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);
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.
When we search for rows which do not meet a criteria we use the criteria with a not modifier.
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)
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
SELF JOIN
SubQuery
Query inside another query is subquery. It is used to get information which is dependent on
another query’s output
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.
“ ”
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
When you write a stored procedure in MySQL, you can pass the input parameters and declare
the local variables:
(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.)
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.
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.
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
Cursor
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:
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);
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 ;
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");
}
OUTPUT
Created table
With correct libraries the program will compile and run well.
Output
Create a table
if (con == NULL) {
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}
mysql_close(con);
exit(0);
}
Program when run won’t show any output. Verify it from command line
if (con == NULL) {
fprintf(stderr, "mysql_init() failed\n");
exit(1);
}
if (result == NULL) {
finish_with_error(con);
}
MYSQL_ROW row;
printf("\n");
}
mysql_free_result(result);
mysql_close(con);
exit(0);
}
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"]
}
)
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
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
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
Database Creation
#use the mysql driver
import mysql.connector
for x in mycursor:
print(x)