11. Tasks
• Complete the classes with methods by dividing them
into sub-tasks.
Example:
Module- Customer registration
Classes-view, service, DB, Customer bean
Methods-
• saveDetails()-return value Customer id
• fetchDetails(custID) - return Customer details object
• Show the return customer id or error message in a
page
11
12. Package
Packages are nothing more than the way we organize files
into different directories according to their functionality,
usability as well as category they should belong to.
12
23. • You have to import classes EmployeeBean, DB.AddEmployee
since service layer deals with database layer and bean class.
• Code for service layer is:
import com.baabtra.bean.EmployeeBean;
import com.baabtra.DB.AddEmployee;
public class AddEmployeeService {
public String registerEmployee(EmployeeBean emp)
{
AddEmployee register= new AddEmployee();
String returnmsg=register.registerEmployeeDB(emp);
return returnmsg;
}
}
23
24. Presentation layer
• Post data to page register.jsp
• Import required classes to register.jsp
<%@ page import="com.Pharma.bean.EmployeeBean"%>
<%@ page import="com.Pharma.Service.AddEmployeeService"%>
• Store data in variables
<%
String employee_id =request.getParameter("employee_id");
System.out.println("Employee Id :"+employee_id);
String employee_name =request.getParameter("employee_name");
String user_name =request.getParameter("user_name");
String employee_password =request.getParameter("employee_password");
String address =request.getParameter("address");
String gender=request.getParameter("gender");
String dob =(String)request.getParameter("txt_dob");
%>
24
25. • Create object form employee bean and set
values for its properties
<%
EmployeeBean emp=new EmployeeBean();
emp.setEmpId(employee_id);
emp.setEmpName(employee_name);
emp.setUserName(user_name);
emp.setPaassword(employee_password);
emp.setAddress(address);
emp.setGender(gender);
emp.setDob(dob1);
emp.setDoj(doj1);
%>
25
26. • Create object for service class and call the
method for registering the employee
<%
AddEmployeeService add= new AddEmployeeService();
String result= add.registerEmployee(emp);
%>
• Check the result and do the necessary action
if (result.equals("Success")){.
//Redirect to page for success
response.sendRedirect("Employee.jsp");
}
else{
out.println("Data not saved");
}
%>
26
28. JDBC
• The JDBC (Java Database Connectivity) API helps a Java
program to access a database in a standard way
• JDBC is a specification that specifies two things
1. tells the database vendors how to write a driver program to
interface Java programs with their database
2. tells the programmers how to write a Java program to access any
database
• A Driver written according to this standard is
called the JDBC Driver
• All related classes and interfaces are present
in the java.sql package
28
29. • The steps involved in a database interaction
are:
– Loading the specific driver(there are different
drivers for different DB)
– Making a connection to the database using the
predefined methods in the java.sql package
– Sending and executing SQL statements to the
database
– Processing the results
29
30. Step1: Load the database Driver
• Load the driver class by calling Class.forName()
with the Driver class name as an argument.
• Once loaded, the Driver class creates an instance
of itself in the memory from which it is then used
• The General format is :
Class.forName( String ClassName );
• Example :
Class.forName ("com.mysql.jdbc.Driver");
30
31. Step2: Setting Connection using Driver
Manager class
– Driver Manager Manages all the JDBC Drivers that
are loaded in the memory
– Its getConnection() method is used to establish a
connection to a database.
– It uses a username, password, and a jdbc url to
establish a connection to the database and returns
a connection object.
Connection connection
=DriverManager.getConnection (url , username,
password);
31
32. Connection conn =null;
String username = "root";
String password = "";
String url = "jdbc:mysql://localhost/project";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url,
userName, password);
DB ip
address Database
name
32
33. Step3:Create a Statement object
• After a connection is obtained we can interact with the
database.
• We use methods defined in Connection interface for
interacting with the database via the established
connection.
• To execute SQL statements, we need to instantiate a
Statement object from the connection object by using
the createStatement() method.
Statement statement = connection.createStatement();
• A statement object is used to send and execute SQL
statements to a database.
33
34. Statement interface
• Defines methods that are used to interact with database via the execution
of SQL statements.
• The different methods are:
– executeQuery(String query) - executes an SQL statement (SELECT) that
queries a database and returns a ResultSet object.
– getResultSet() - used to retrieve the ResultSet object
– executeUpdate(String query) - executes an SQL statement (INSERT ,UPDATE
or DELETE) that updates the database and returns an integer value which
specifies the number of rows modified
– execute(String query) - executes an SQL statement that is written as String
object
34
35. ResultSet Interface
• Maintains a pointer to a row within the tabular results obtained .
• The next() method is used to iterate through the rows of the tabular
results. Initially the iterator is initialized to a position before the first row.
Hence we have to call next() once to move it to the first row.
• The different methods are:
– getBoolean(int) - Get the value of a column in the current row as a Java
boolean.
– getDouble(int) - Get the value of a column in the current row as a Java
double.
– getInt(int) - Get the value of a column in the current row as a Java int.
– getString(String)-Get value as java string
35
36. Database connection class
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
public class
{//declare connection as instance variable
public Connection conn;
public Dbconnection()
{ //constructor for the class
String url="jdbc:mysql://localhost:3306/";
String dbname=“database_name";
String driver="com.mysql.jdbc.Driver";
String dbusername="root";
String dbpassword="baabtra";
try {
Class.forName(driver).newInstance();
conn=(DriverManager.getConnection(url+dbname,dbusername,dbpassword);
System.out.println("connected......");
} catch (Exception e) {
System.out.println(e.getMessage()); 36
37. Creating DB layer
• Create a method inside AddEmployee class
public String registerEmployeeDB(EmployeeBean emp)
{
}
• Strip the object ‘emp’ to get values and store it in
variables
String employee_id=emp.getEmpId();
String employee_name=emp.getEmpName();
String user_name=emp.getUserName();
String employee_password=emp.getPaassword();
String address=emp.getAddress();
String gender=emp.getGender();
String dob=emp.getDob();
String doj=emp.getDoj();
37
39. Do the database operation for
registering the employee
//insert data into login table
String sqlQuery ="insert into tbl_login(user_name, password,role)"+
"values('"+user_name+"',
'"+employee_password+"','EMPLOY')";
int Count=st.executeUpdate(sqlQuery) ;
//Check whether data is inserted or not
if (Count>0)
{
int id=0;
//select currently inserted id (auto increment )from login table
ResultSet rs=st.executeQuery("select max(pk_login_id) as id from
tbl_login ");
while(rs.next()){
id=rs.getInt("id");
}
39
40. //Insert data to employee table
sqlQuery="insert into
tbl_employe(pk_employee,fk_loginid,emp_first_name,emp_addres, "+
"emp_gender,emp_dob,emp_doj) values('"+employee_id+"',"+
id+",'"+employee_name+"','"+
address+"','"+gender+"','"+dob+"','"+doj+"')";
int Count1=st.executeUpdate(sqlQuery);
//Return success or fail depending on status of database operation
if (Count1>0){
return "Success";
}}
else
{
return "Fail";
}
40
41. Selecting and displaying data from
database using list
• Create method for getting data in database
layer
public List getEmployeeListDB(){
//code for connecting to database
//declarea list of Employee bean
//do the database operation (select data from database)
//store the result set in the list
//pass it to service layer
}
41
42. //Declare list of employee bean
List<EmployeeBean > details=new ArrayList<EmployeeBean >();
ResultSet rs=s.executeQuery("Select * from employees");
//loop to fetch the query results one by one
while(rs.next()){
//ceating object to save each row details
EmployeeBean emp=new CustomerBean();
emp.setName(rs.getString("name"));
emp.setAddress(rs.getString("address"));
emp.setEmail(rs.getString("email"));
//adding the objects to the list object that was made
details.add(emp);
}
conn.close();
//returning the list with objects
return details;
42
43. Code in service class
import java.util.List;
import com.babte.DB.Employee;
public class EmployeeService {
public List getEmployeeListService()
{
EmployeeDB ObjEmp=new EmployeeDB();
List list=ObjEmp. getEmployeeListDB();
return list;
}
}
43
47. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
48. Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com