Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

February 21, 2020

Department wise employees having salary greater than average salary


Correlation subqueries

 Let us consider an employee table and department table. For readers simplicity we are just giving minimum fields in the table/

Table employees


/*Table structure for table `tbl_employee` */

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `salary` double DEFAULT NULL,
  `department_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)

/*Data for the table `tbl_employee` */

insert  into `tbl_employee`(`id`,`name`,`salary`,`department_id`) values (1,'Sachin',2500,1),(2,'Dravid',9000,1),(3,'Ganguly',7000,1),(4,'Azaruddin',10000,1),(5,'Jadeja',8000,2),(6,'Sreenath',9500,2),(7,'Rohit',7800,2),(8,'Kambli',4000,2),(9,'Kapil',10001,3),(10,'Kohli',2300,2),(11,'Pant',3400,1);


Table Employees



Table department



/*Table structure for table `tbl_departments` */


CREATE TABLE `tbl_departments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;


/*Data for the table `tbl_departments` */

insert  into `tbl_departments`(`id`,`name`) values (1,'ODI'),(2,'TEST'),(3,'T20'),(4,'IPL');

Table department

Query 1 : Select all employees whose salary is greater than average salary of all departments


select * from tbl_employee where salary > (select avg(salary) from tbl_employee)

will return all the employees having the salary greater than the average salary ie 6681.91




Query 2 : Select employees whose salary is greater than their departments average salary


SELECT * FROM tbl_employee e1 where salary > (select AVG(salary) from tbl_employee e2 where e2.department_id = e1.department_id)

will returns the  department wise employees having the salary greater than the average salary




Query 3 : Select top two employees having higher salaries in their department



SELECT * FROM tbl_employee e1 WHERE 2 >  (SELECT Count(DISTINCT salary) FROM tbl_employee e2 WHERE e2.Salary > e1.Salary  AND e1.department_id = e2.department_id );

Top 2 salaries in each department

department employees having their higher salaries

Thanking you


November 05, 2018

SQL Where IN Having and Group by Query Sample

customer table



select * from customer where country = 'IN'



select * from customer where country in ('in','us');


select * from customer having country = 'in'




select * from customer GROUP BY country



select customer_name,sum(credit) as balance from customer group by country;



select customer_name,sum(credit) as balance from customer where country in ('in','us','jp');



select customer_name,sum(credit) as balance from customer group by country having balance > 1800;



Thank you..

October 26, 2017

Sample Mysql Trigger on product inventory


Sample Mysql Trigger on product inventory


DELIMITER $$

DROP TRIGGER /*!50032 IF EXISTS */ `db_inventory_datacom`.`UpdateInventoryOnSalesReturn`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `UpdateInventoryOnSalesReturn` AFTER INSERT ON `tbl_prdt_sales_returns`
    FOR EACH ROW begin
update tbl_inventories set prod_quantity=(prod_quantity + new.prdt_quantity),prod_reorder_date=curdate() where prod_id=new.prod_id;
    END;
$$

DELIMITER ;

The event triggers when ever a new row is inserted in  the table `tbl_prdt_sales_returns`.

The trigger will update the table  tbl_inventories  product quantity .

April 03, 2017

MySql sample stored procedures

if else update insert stored procedure


DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `cfedapps`.`p_save_branch`(in branchId int(50),in branchCode int(5),in branchName varchar(55),in address varchar(55),in district varchar(33),in pincode bigint(10),in landline bigint(15),in startDate date,in lat long,in lon long, in branchStatus varchar(5), in branchDesc varchar(55),in userId int(4), in imgUrl varchar(55),in branchEmail varchar(55),in branchType int(5))
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
    BEGIN
 
if (branchId is not null) then

update tbl_unit_details set firmCode = branchCode,unitName = branchName where unitId = branchId;

else

insert into tbl_unit_details (firmCode,unitName,address,district,pincode,landline,startedDate,unitLat,unitLon,status,description,userId,unitImg,branchEmailid,unittype) values (branchCode,branchName,address,district,pincode,landline,startDate,lat,lon,branchStatus,branchDesc,userId,imgUrl,branchEmail,branchType);
select last_insert_id();

end if;

    END$$

DELIMITER ;


Important notes


Setting default value of a column to CURRENT_TIMESTAMP while creating a database allows to update current date time in that field automatically

sample query
create table consumerfed (itsection varchar(32),createdDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP);


Thanks

http://javabelazy.blogspot.in/

August 05, 2014

How to write stored procedure in mysql

How to call MySql stored procedure form java application


There are 3 types of stored procedures
  • system stored procedures
  • extended stored procedure
  • user defined stored procedures
Stored procedure allow modular programing, faster execution, reduce traffic, security to your data

Create a table named states

/*Table structure for table `tbl_states` */

DROP TABLE IF EXISTS `tbl_states`;

CREATE TABLE `tbl_states` (
  `stateId` int(11) NOT NULL AUTO_INCREMENT,
  `state` varchar(25) NOT NULL,
  `status` varchar(10) NOT NULL DEFAULT 'Y',
  PRIMARY KEY (`stateId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;


Stored procedure for inserting values to states

Procedure name : p_states_insertstates
Input : statename and status of state

/* Procedure structure for procedure `p_states_insertstates` */

/*!50003 DROP PROCEDURE IF EXISTS  `p_states_insertstates` */;

DELIMITER $$

/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `p_states_insertstates`(In i_state VARCHAR(25),in i_status varchar(10))
BEGIN
    insert into tbl_states(state,status) values (i_state,i_status);
    Select last_insert_id();
    END */$$
DELIMITER ;



insert query : insert  into `tbl_states`(`stateId`,`state`,`status`) values (1,'Sakha Republic','N');

Java Code : callable insertion


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class Main {
       public static Connection connections()
        {
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost/whatsAppdatabase","root","root");
                return con;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Main m = new Main();
        m.insert("SakhaRepublic","Y");
    }
    private void insert(String stateName, String stateStatus) {
        String state = stateName;
        String status = stateStatus;
        CallableStatement statement = null;
      
        Connection connect = Main.connections();
        System.out.println(" connecting .... ");
        String sql = "{call p_states_insertstates (?, ?)}";
        try {
            statement = connect.prepareCall(sql);
            statement.setString(1, state);
            statement.setString(2, stateStatus);
            //statement.registerOutParameter(3, java.sql.Types.VARCHAR);
            statement.execute();
            //int empName = statement.getInt(3);
            System.out.println(" id : ");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            try {
                statement.close();
                connect.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          
        }
      
      
    }
}


Example of Mysql stored procedure with OUT parameter


DELIMITER $$
CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `serviceinformata`.`test`(out id int)
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
    BEGIN
    Select Max(stateId) into id from tbl_states;
    END$$
DELIMITER ;

replace the above function with this

    private void insert(String storedProcedure, String ,mysqlExample) {
        String state = stateName;
        String status = stateStatus;
        CallableStatement statement = null;
       
        Connection connect = Main.connections();
        System.out.println(" connecting .... ");
        String sql = "{call test (?)}";
        try {
            statement = connect.prepareCall(sql);

            statement.registerOutParameter(1, java.sql.Types.INTEGER);
            statement.execute();
            int stateId= statement.getInt(1);
            System.out.println(" id : "+stateId);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            try {
                statement.close();
                connect.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
      }

You have to download mysql connector.jar download link


This is a small example for insertion stored procedure in mysql and how to call it from your java application

Advantage of stored procedures

  1. performance
  2. productivity and ease of use
  3. scalability
  4. maintainability
  5. interoperability
  6. security
  7. replication

Possible Exceptions

Data too long for column 'column_name'

http://javabelazy.blogspot.in/

August 05, 2012

Compare database mysql date with current date

 Comparing mysql database date with current java date
/**
 *
 */
package Date;



import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author deep
 *
 * program compares todays date with that in db
 *
 */






public class JavaDate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String dateInDB = "2011-1-12";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = format.format(new Date());
        System.out.println(" Current date : " +currentDate);
        System.out.println(" date in db   : " +dateInDB);
        if(currentDate.compareTo(dateInDB) <= 0)
            System.out.println("current date is greater ");
        else
            System.out.println("db date is greater ");
    }

}


Thanking you....

January 14, 2010

Student Application Java web application using Servlet Mysql JSP - Athul kannoth


How the request goes ?

The first page executed will be  welcome file in web.xml  then to JSP page , the user click on submit button particular servlet will be called which is specified in the action tag. The request created (example shown by ***) will be reached at web.xml, where we specified servlet mapping. thus it identifies which servlet will be called. since we uses get method, request reaches doGet method inside the servlet.

After getting request parameter using request.getparameter, we assign the values to student pojo object ( to pass the value to insert query inside dao).

Once the request reach dao, we create a connection object for connecting to mysql database, where we need to specifies vendor name, database location, database name, and credential to access the database.

Sql queries are exceuted by Java ( java data base connectivity - JDBC) using a preparestatement.

Thus insert the value to database. Once inserted we will " successfull inserted " message to Users

For that we use the following method inside servlet

response.getWriter().append(message).append(request.getContextPath());

this is the response to user ( ie response will be send back to jsp -java server page)




0. Welcome file (web.xml)

 <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

List of welcome file to be mentioned in the studentapp. which is the entry page of the application.


1. Inside JSP page (file Name : index.jsp)

<form action="StudentServlet">

Please enter the name of Student <input type="text" name="name" /><br>
Please enter the roll NO of Student <input type="text" name="rollNo" /><br>
Please enter the age of Student <input type="text" name="age" /><br>
Please enter the class of Student <input type="text" name="stream" /><br>
<input type="submit" value="submit">

</form>

This is called form action. Once user submit a button  the request will be send to the particular servlet mention in the form action.

*** Request : http://localhost:8080/StudentApp/StudentServlet?name="athul"&age="25"&stream="tcs"&rollno="1224"


2. Inside deployment descriptor ( web.xml)

<servlet>
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>com.konzern.studentapp.servlets.StudentServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/StudentServlet</url-pattern>
  </servlet-mapping>

This is called servlet mapping - mapping a particular url (http request) to a servlet.





StudentServlet ( Servlet class)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/
Student student = new Student();
student.setName(request.getParameter("name"));
student.setRollNo(Integer.parseInt(request.getParameter("rollNo")));
student.setAge(Integer.parseInt(request.getParameter("age")));
student.setStream(request.getParameter("stream"));

StudentDAOservice = new StudentDAO();
String message = service.insert(student);

response.getWriter().append(message).append(request.getContextPath());
}

Once the http request reaches the servlet, the parameters in the http url are get using request.getparameter("name");

The parameters are encapsulated to a student POJO, to data transfer the data inside the application
here in our case to DAO packages.

Student Object will be send to StudentDAO insert method.

Student ( POJO Class)

/**
 *
 */
package com.konzern.studentapp.model;

/**
 * @author Gokul Balan
 *
 */
public class Student {

private String name =null;
private int rollNo = 0;
private int age = 0;
private String stream= null;


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
}



StudentDAO.java ( Data access Objects)

public String insert(Student student) throws SQLException {
PreparedStatement p= MySQLConnection.prepareStatement(" insert into ipmanagetable(name,age,rollno,class) values(?,?,?,?)");
p.setString(1,student.getName());
p.setInt(2,student.getAge());
p.setInt(3, student.getRollNo());
p.setString(4, student.getStream());
int output = p.executeUpdate();
return "Student information saved";
}


Here is where we use to write queries to insert, update, delete operations ( SQL queries ).

We use PrepareStatement in JDBC to write sql queries.

PreparedStatement.execute(); method will exceute the sql query.


MySQL Connection class


public static Connection connectionInstance() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =  DriverManager.getConnection("jdbc:mysql://localhost/StudentAppDb", "username", "password");
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

You need to specify which driver you are using
Class.forName("com.mysql.jdbc.Driver");

For different database vendors the driver names will be different .

com.mysql.jdbc.Driver is for mysql.

In DriverManager.getConnection, you need to specify database vendor:// location of database/ database name in additional to authentication credentials ie username & password.



Thanks
Athul Kannoth


For any queries feel free to contact us.
















January 07, 2010

Student Management Apps - Web application | Complete source code

Index.JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student Details Entering page</title>

</head>
<body>

<form action="StudentServlet">

Please enter the name of Student <input type="text" name="name" /><br>
Please enter the roll NO of Student <input type="text" name="rollNo" /><br>
Please enter the age of Student <input type="text" name="age" /><br>
Please enter the class of Student <input type="text" name="stream" /><br>
<input type="submit" value="submit">

</form>

</body>
</html>


Web.xml ( Deployment Descriptor)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>StudentApp</display-name>
 
 <!--   <servlet>
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>com.konzern.studentapp.servlets.StudentServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/StudentServlet</url-pattern>
  </servlet-mapping> -->
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>



Student Servlet

package com.konzern.studentapp.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.konzern.studentapp.model.Student;
import com.konzern.studentapp.service.StudentService;
import com.konzern.studentapp.service.StudentServiceInf;

/**
 * Servlet implementation class StudentServlet
 */
@WebServlet(description = "Student Details servlet", urlPatterns = { "/StudentServlet" })
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Student student = new Student();
student.setName(request.getParameter("name"));
student.setRollNo(Integer.parseInt(request.getParameter("rollNo")));
student.setAge(Integer.parseInt(request.getParameter("age")));
student.setStream(request.getParameter("stream"));
StudentServiceInf service = new StudentService();
String message = service.insert(student);
response.getWriter().append(message).append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}


Student POJO object

/**
 * 
 */
package com.konzern.studentapp.model;

/**
 * @author Athul kannoth
 *
 */
public class Student {
private String name =null;
private int rollNo = 0;
private int age = 0;
private String stream= null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}

}


Student Service


/**
 * 
 */
package com.konzern.studentapp.service;

import com.konzern.studentapp.model.Student;

/**
 * @author Athul kannoth
 *
 */
public interface StudentServiceInf {
public String insert(Student student);

}

/**
 * 
 */
package com.konzern.studentapp.service;

import java.sql.SQLException;

import com.konzern.studentapp.dao.StudentDAO;
import com.konzern.studentapp.dao.StudentDAOInf;
import com.konzern.studentapp.model.Student;

/**
 * @author Gokul balan
 *
 */
public class StudentService implements StudentServiceInf {
private StudentDAOInf studentDaoInf = null;
private StudentDAOInf getStudentDAO() {
studentDaoInf = new StudentDAO();
return studentDaoInf;
}

@Override
public String insert(Student student) {
try {
return getStudentDAO().insert(student);
// return "success";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Technical Failure";
}

}


Student DAO

/**
 * 
 */
package com.konzern.studentapp.dao;

import java.sql.SQLException;

import com.konzern.studentapp.model.Student;

/**
 * @author Apple
 *
 */
public interface StudentDAOInf {
public String insert(Student student) throws SQLException;

}


/**
 * 
 */
package com.konzern.studentapp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.konzern.studentapp.model.Student;

/**
 * @author Kouta
 *
 */
public class StudentDAO implements StudentDAOInf {
private Connection getConnection() {
return  MysqlConnection.connectionInstance();
}

@Override
public String insert(Student student) throws SQLException {
PreparedStatement p= getConnection().prepareStatement(" insert into ipmanagetable(ipadd,port,date) values(?,?,?)");
p.setString(1,student.getName());
p.setInt(2,student.getAge());
p.setInt(3, student.getRollNo());
p.setString(4, student.getStream());
int output = p.executeUpdate();
return "Student information saved";
}

}


MySQL Connection Class


/**
 * Arjun babu 
 */
package com.konzern.studentapp.dao;

import java.sql.DriverManager;
import java.sql.Connection;

/**
 * @author Arjun babu
 *
 */
public class MysqlConnection {

public static Connection connectionInstance() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =  DriverManager.getConnection("jdbc:mysql://localhost/StudentAppDb", "username", "password");
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}



For Complete explanation ( Full source code explain )








Facebook comments