SlideShare uma empresa Scribd logo
1 de 79
OBTAINING A CONNECTION TO DATABASE
• Approach1: Directly using Driver object
OBTAINING A CONNECTION TO DATABASE
STEP 1(approach1) 1.JPG
/*
Jdbc first Example
we want to write a java program to create a new record with the following
values into the database table
emp:
empno: 101
ename: e101
salary:1000
deptno:10
Considering the following table in oracle database to exist
create table emp(empno number, ename varchar2(20), sal number(10,2),
deptno number);
*/
//JdbcExample1.java
• //JdbcExample1.java
import java.sql.*;
import java.util.Properties;
public class JdbcExample1
{
public static void main(String args[]) throws Exception
{
//we want to create a new record, to do this we want to execute the following sql to the database
String sql="insert into emp values(101,'e101',1000,10)";
String driverClassName="oracle.jdbc.driver.OracleDriver";
Class c=Class.forName(driverClassName);
Driver d=(Driver)c.newInstance();
//STEP 1.2: TYPE -2 DRIVER, thin is a name of the driver
String JdbcUrl="jdbc:oracle:thin:@localhost:1521:XE";
Properties dbprops=new Properties();
dbprops.put("user","system");
dbprops.put("password","manager");
Connection con=d.connect(JdbcUrl,dbprops);
Statement st=con.createStatement();
st.executeUpdate(sql);
//step 4:
con.close();
System.out.println("record is saved");
}
}
Work flow of JDBC
How to run this program:
/*
you need to have the following softwares installed in the machine:
(1) JDK
(2) Oracle DB
Now perform the following to get this example run:
(1) create the table in the DB:
We can run the above mentioned create table SQL Statement using the
SQL* plus Editor.
(2) set ojdbc14.jar (or) ojdbc5.jar (or) ojdbc6.jar into the classpath.
we can find this jar file in the oracle install folder.
Note
: In this example we are working with Oracle's JDBC Type-4
Driver
Note: (b)
Here our intention is to execute the query that is step 4 (
executeUpdate(sql))
But it is Method method of statement so I must crate
Statement object to execute the Query, here Statement
object acts as a vehicle which carries sql query to Database
So I’m creating Statement object, for creating statement
object I must call createStatement() method, which is a
member method of Connection object.
So for to do this we are creating Connection object
Q:What is classpath?
classpath: is a system variable to specify the
location of resources (Ex: .class) to locate by
the java
compiler & the Application class Loader
Q:How to set class path? It depends on
Operating System:
In windows:
(1) using system environment variables setting
window
(2) using 'set' internal command
D:materialjava(E DRIVE)javaAdvJavajdbc>javac JdbcExample1.java
D:materialjava(E DRIVE)javaAdvJavajdbc>set classpath=c:oraclexeappo..... ;.;
Q: why .(dot) directory should be specified in the classpath?
Ans:
Because classloader tries to search even our current program (Ex: JdbcExample1.class) file in the Oracle
install folder which we are specifieing, but this is our program which is available only E: drive..with
some other location so we will get error, to avoid this problem we are informing to the class loader that
our current program (Ex: JdbcExample1.class) is available in the current directory (ie. Ex:
D:materialjava(E DRIVE)javaAdvJavajdbc)
Q: What are The possible problems we may get in running this program?
Ans:
1. ClassNotFoundException:
oracle.jdbc.driver.OracleDriver
to solve this problem we just need to set ojdbc.jar file into the classpath.
2. TNS: listener does not currently know of SID:
THIS error is raised when we use wrong service id in
the URL.
How to find the correct ServiceId?
Ans:
we have multiple ways, the one simple way is find it
from the Windows Services
(control->services->OracleServiceXE..)
We find a service with the name
OracleService<ServiceID> (Ex: ServiceID=XE)
Q: What are the changes can be done to work with
Oracle's JDBC TYPE-2 Driver?
Q: What are the changes can be done to work
with Oracle's JDBC TYPE-2 Driver?
Ans:
The Oracle's JDBC Driver Type-2 and Type-4 Drivers
are implemented into a single Driver
implmentation
class so we don't need to change the driver class.
Only that we need to change is JDBCURL.
In the previous example (i.e: JdbcExample1.java)
change the JDBC URL to:
String JdbcUrl="jdbc:oracle:oci:@XE";
Q: HOW TO RUN THIS PROGRM (USING TYPE-2)?
Ans:
classpath same as described earlier:
In addition we need to set the oracle bin folder
into path:
set
path=c:oraclexeappproduct10.0.2serverbin;
%path%
*/
Q:what is %path%?
•
• Ans: now we are setting the class path that
means already we may set other class path
also, but I don’t want to overwrite previous
class path, I want to concatenate the previous
class path , that can be done by using this
%path%
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
Using JDBC in the Project (Project Architecture)
with DAO Design Pattern
What is Low Level Persistence Logic?
• Low Level means it is specific to one type of dependent persistence logic
• Persistence Logic: is responsible for accessing persistence Data
• If I’m using low level persistence logic in Business Logic (i.e High Level
Logic) so I can not connect to all the Back end servers.
• To avoid this problem we have to use another layer , keep the persistence
logic in a separate object, that object is nothing but a Data Access Object
(DAO).
•
• SO here DAO is a Design Pattern, Design Pattern which gives a solution for
a problem.
• (Example: I’m facing a problem, I will try to interact with a friend who is
already faced the problem because he will have ready made solution for
that problem, no need to waste my time to solve the problem, because
already ready made solution (design pattern) is available
What is Low Level Persistence Logic?
Introducing DAO
• When it comes into the project (enterprise
application) we need to concentrate in
optimizing the code, making the more
reusable, and also testable.
• The DAO is the most common pattern
implemented into the enterprise applications.
What is a Pattern?
• Pattern is a three part document that describes
the context (situation), reoccurring problem and
the best solution for the problem in the given
context (situation).
• The software patterns are categorized into
multiple type for convenience in learning and
applying.
• The design patterns is one of the category. This
lists the patterns describing the problems related
to design and development of the software
applications
THE DAO DESIGN PATTERN:
•
• As the title describes this is a design pattern
• Context (situation):
• We want to create enterprise Application with reasonable business logic having a requirement of accessing
multiple (variety) of datastore and /or found that may have a requirement of migrating from one type of data
store (database) to other. Easy to migrate between the different types of data stores. That is in my application I
want to connect to LDAP to take credentials, same application I want to connect to File Systems to accept login
details.
• Problem:
• We want to separate the low-level persistence (data access) logic from Business Logic. But this so this solution
leaves a problem that is how do you separate in a best way? Thus this solution we kept in a problem.
• Forces: (Why):
• We want to have a proper responsibility division that is:
• (a) improves the quality of the system.
• (b) reduces the cost and time for the development
• To enable unit testing, make the system more comfortable for testing.
• Easy to migrate between the different types of data stores.
• Solution:
• Implement the low-level persistence logic into a separate object, exposing the data access operations through
high-level API to the service layer.
What is DAO ?
• Ans: DAO is a design pattern that describes
separating the low-level persistence logic from
the business logic, implementing into a
separate (independent) object.
•
• Note: this special object introduced
implementing the DAO pattern is also refered
as a DAO i.e: Data Access Object
• From this discussion and the above
architecture we understand JDBC is used for
implementing the DAO in Java for accessing
the tabular data store
Use Case diagram of our project
Implementing DAO Design Pattern in
our project
Implementing the Data Access Layer for ‘CreateEmployee’ use
case of ‘Employee Management System (EMS).
• For Example:
• Implementing the Data Access Layer for ‘CreateEmployee’ use case of ‘Employee Management System (EMS).
•
• //EmployeeDAOI.java
• package com.st.ems.dao;
• public interface EmployeeDAOI
• {
• void save(int eno,String name, double sal, int dno);
• //we will change this struture later
• //we will add some more methods as we proceed
• }
•
•
• //EmployeeDAO.java
• package com.st.ems.dao.jdbc;
• import com.st.ems.dao.EmployeeDAOI;
• import java.sql.*;
• import java.util.*;
• public class EmployeeDAO implements EmployeeDAOI
• {
• public void save(int eno, String name,double sal, int dno)
• {
• //this method is responsible for saving the given details into emp table
• //to do: execute the following SQL
• String sql="insert into emp values("+eno+",'"+name+",',"+sal+","+dno+")";
• //how to execute?
• //use JDBC
• //Write this Connection con=null here only to make visible to all the blocks
• Connection con=null;//null is necessary whn u r declaring as a local variable
• try
• {
• //step 1.1
• String driverClassName="oracle.jdbc.driver.OracleDriver";//here we are using oracle driver
• Class c=Class.forName(driverClassName);
• Driver d=(Driver)c.newInstance();
• //step 1.2
• String jdbcUrl="jdbc:oracle:thin:@localhost:1521:XE";
• Properties p=new Properties();
• p.put("user","system");
• p.put("password","manager");
• //Connection con=null;//i can not use con ref variable in finally block as it is local to this
• block
•
•
• con=d.connect(jdbcUrl,p);
• //step2
• Statement st=con.createStatement();
• //step3
• st.executeUpdate(sql);
•
•
• }//end of try block
• catch(Exception e)
• {
• e.printStackTrace();
• //to report the error, we will set run time error
• throw new RuntimeException(e);
• }
• finally
• {
• try
• {
• //step 4:
• con.close();
•
• }//try
• catch(Exception e){}
• }//finally
•
•
• }//save
• }//class
• /* now we are writing Tese case for DAO object [that is save()] for this we have to use JUNIT but
• we are using main() for this application
• */
• //EmployeeDAOTestCase.java
• import com.st.ems.dao.jdbc.EmployeeDAO;
• import com.st.ems.dao.EmployeeDAOI;
•
•
• public class EmployeeDAOTestCase
• {
• private EmployeeDAOI edao;
• public void testsave()
• {
• edao.save(102,"e102",20000,20);
• System.out.println("Details saved");
• }
• public static void main(String s[])
• {
• EmployeeDAOTestCase test=new EmployeeDAOTestCase();
• test.edao=new EmployeeDAO();
• test.testsave();//here Driver object is created
• //test.testsave();//here 2nd Driver object is created but one Driver object is enought to handle
• //multiple request from diffrent clients, connections as it is a Thread -safe
• }
• }
• /*
• D:materialjava(E DRIVE)javaAdvJavajdbcDAO>javac
-d . *.java
• D:materialjava(E
DRIVE)javaAdvJavajdbcDAO>D:materialjava(E
• DRIVE)javaAdvJavajdbcDAO>set
classpath=C:oraclexeappor
• acleproduct10.2.0serverjdbclibojdbc14.jar;.;
• D:materialjava(E DRIVE)javaAdvJavajdbcDAO>java
EmployeeDAOTestCase
• Details saved
• */
Q: is our DAO created efficient?
• Ans: No, we need to multiple changes. Let us look into all of them
one after the other
• In the EmployeeDAO created earlier the save() method is
programmed to create a new instance (object) of Driver class on
every request, which is not effective.
• Considering the following points with respect to the Driver:
• The Driver object is Thread-safe means Driver object performs
consistently even on concurrent requests from multiple threads
• A single instance of Driver can be used to create multiple
connections because it is Thread-safe. If we create the multiple
instances of Driver class, unnecessarly garbage is stored into the
memory, and performance becomes slow.
• Considering these points a single instance of Driver is enough for an
application per data base.
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1
4 jdbc step1

Mais conteúdo relacionado

Mais procurados

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...Pallepati Vasavi
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionMazenetsolution
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)Maher Abdo
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servletsNuha Noor
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
Java.sql package
Java.sql packageJava.sql package
Java.sql packagemyrajendra
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statementmyrajendra
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 

Mais procurados (20)

JDBC
JDBCJDBC
JDBC
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
Jdbc
JdbcJdbc
Jdbc
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC
JDBCJDBC
JDBC
 

Destaque (20)

Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Java stereams
Java stereamsJava stereams
Java stereams
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
 
Get data
Get dataGet data
Get data
 
Get excelsheet
Get excelsheetGet excelsheet
Get excelsheet
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Interface connection
Interface connectionInterface connection
Interface connection
 
Different waysconnect
Different waysconnectDifferent waysconnect
Different waysconnect
 
Class
ClassClass
Class
 
Class
ClassClass
Class
 
Forms
FormsForms
Forms
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
Record store
Record storeRecord store
Record store
 
Headings
HeadingsHeadings
Headings
 
Wr ex2
Wr ex2Wr ex2
Wr ex2
 
Driver
DriverDriver
Driver
 

Semelhante a 4 jdbc step1

EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivityarikazukito
 
Testing database content with DBUnit. My experience.
Testing database content with DBUnit. My experience.Testing database content with DBUnit. My experience.
Testing database content with DBUnit. My experience.Serhii Kartashov
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part ISivaSankari36
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5phanleson
 
BITM3730Week13.pptx
BITM3730Week13.pptxBITM3730Week13.pptx
BITM3730Week13.pptxMattMarino13
 
Obevo Javasig.pptx
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptxLadduAnanu
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
Java database programming with jdbc
Java database programming with jdbcJava database programming with jdbc
Java database programming with jdbcsriram raj
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Som Prakash Rai
 

Semelhante a 4 jdbc step1 (20)

Jdbc
JdbcJdbc
Jdbc
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Data access
Data accessData access
Data access
 
Jdbc
JdbcJdbc
Jdbc
 
Testing database content with DBUnit. My experience.
Testing database content with DBUnit. My experience.Testing database content with DBUnit. My experience.
Testing database content with DBUnit. My experience.
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
 
BITM3730Week13.pptx
BITM3730Week13.pptxBITM3730Week13.pptx
BITM3730Week13.pptx
 
Obevo Javasig.pptx
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptx
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Java database programming with jdbc
Java database programming with jdbcJava database programming with jdbc
Java database programming with jdbc
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 

Mais de myrajendra

Mais de myrajendra (11)

2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 
Properties
PropertiesProperties
Properties
 
Interface result set
Interface result setInterface result set
Interface result set
 
Interface database metadata
Interface database metadataInterface database metadata
Interface database metadata
 
Indexing
IndexingIndexing
Indexing
 
Exceptions
ExceptionsExceptions
Exceptions
 

Último

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 

Último (20)

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 

4 jdbc step1

  • 1. OBTAINING A CONNECTION TO DATABASE • Approach1: Directly using Driver object
  • 4. /* Jdbc first Example we want to write a java program to create a new record with the following values into the database table emp: empno: 101 ename: e101 salary:1000 deptno:10 Considering the following table in oracle database to exist create table emp(empno number, ename varchar2(20), sal number(10,2), deptno number); */
  • 5. //JdbcExample1.java • //JdbcExample1.java import java.sql.*; import java.util.Properties; public class JdbcExample1 { public static void main(String args[]) throws Exception { //we want to create a new record, to do this we want to execute the following sql to the database String sql="insert into emp values(101,'e101',1000,10)"; String driverClassName="oracle.jdbc.driver.OracleDriver"; Class c=Class.forName(driverClassName); Driver d=(Driver)c.newInstance(); //STEP 1.2: TYPE -2 DRIVER, thin is a name of the driver String JdbcUrl="jdbc:oracle:thin:@localhost:1521:XE"; Properties dbprops=new Properties(); dbprops.put("user","system"); dbprops.put("password","manager"); Connection con=d.connect(JdbcUrl,dbprops); Statement st=con.createStatement(); st.executeUpdate(sql); //step 4: con.close(); System.out.println("record is saved"); } }
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18. How to run this program: /* you need to have the following softwares installed in the machine: (1) JDK (2) Oracle DB Now perform the following to get this example run: (1) create the table in the DB: We can run the above mentioned create table SQL Statement using the SQL* plus Editor. (2) set ojdbc14.jar (or) ojdbc5.jar (or) ojdbc6.jar into the classpath. we can find this jar file in the oracle install folder.
  • 19. Note : In this example we are working with Oracle's JDBC Type-4 Driver Note: (b) Here our intention is to execute the query that is step 4 ( executeUpdate(sql)) But it is Method method of statement so I must crate Statement object to execute the Query, here Statement object acts as a vehicle which carries sql query to Database So I’m creating Statement object, for creating statement object I must call createStatement() method, which is a member method of Connection object. So for to do this we are creating Connection object
  • 20. Q:What is classpath? classpath: is a system variable to specify the location of resources (Ex: .class) to locate by the java compiler & the Application class Loader
  • 21. Q:How to set class path? It depends on Operating System: In windows: (1) using system environment variables setting window (2) using 'set' internal command
  • 22. D:materialjava(E DRIVE)javaAdvJavajdbc>javac JdbcExample1.java D:materialjava(E DRIVE)javaAdvJavajdbc>set classpath=c:oraclexeappo..... ;.; Q: why .(dot) directory should be specified in the classpath? Ans: Because classloader tries to search even our current program (Ex: JdbcExample1.class) file in the Oracle install folder which we are specifieing, but this is our program which is available only E: drive..with some other location so we will get error, to avoid this problem we are informing to the class loader that our current program (Ex: JdbcExample1.class) is available in the current directory (ie. Ex: D:materialjava(E DRIVE)javaAdvJavajdbc) Q: What are The possible problems we may get in running this program? Ans: 1. ClassNotFoundException: oracle.jdbc.driver.OracleDriver to solve this problem we just need to set ojdbc.jar file into the classpath.
  • 23. 2. TNS: listener does not currently know of SID: THIS error is raised when we use wrong service id in the URL. How to find the correct ServiceId? Ans: we have multiple ways, the one simple way is find it from the Windows Services (control->services->OracleServiceXE..) We find a service with the name OracleService<ServiceID> (Ex: ServiceID=XE)
  • 24. Q: What are the changes can be done to work with Oracle's JDBC TYPE-2 Driver?
  • 25. Q: What are the changes can be done to work with Oracle's JDBC TYPE-2 Driver? Ans: The Oracle's JDBC Driver Type-2 and Type-4 Drivers are implemented into a single Driver implmentation class so we don't need to change the driver class. Only that we need to change is JDBCURL. In the previous example (i.e: JdbcExample1.java) change the JDBC URL to: String JdbcUrl="jdbc:oracle:oci:@XE";
  • 26. Q: HOW TO RUN THIS PROGRM (USING TYPE-2)? Ans: classpath same as described earlier: In addition we need to set the oracle bin folder into path: set path=c:oraclexeappproduct10.0.2serverbin; %path% */
  • 27. Q:what is %path%? • • Ans: now we are setting the class path that means already we may set other class path also, but I don’t want to overwrite previous class path, I want to concatenate the previous class path , that can be done by using this %path%
  • 28. Using JDBC in the Project (Project Architecture)
  • 29. Using JDBC in the Project (Project Architecture)
  • 30. Using JDBC in the Project (Project Architecture)
  • 31. Using JDBC in the Project (Project Architecture)
  • 32. Using JDBC in the Project (Project Architecture)
  • 33. Using JDBC in the Project (Project Architecture)
  • 34. Using JDBC in the Project (Project Architecture)
  • 35. Using JDBC in the Project (Project Architecture)
  • 36. Using JDBC in the Project (Project Architecture)
  • 37. Using JDBC in the Project (Project Architecture)
  • 38. Using JDBC in the Project (Project Architecture)
  • 39. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 40. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 41. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 42. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 43. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 44. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 45. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 46. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 47. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 48. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 49. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 50. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 51. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 52. Using JDBC in the Project (Project Architecture) with DAO Design Pattern
  • 53. What is Low Level Persistence Logic? • Low Level means it is specific to one type of dependent persistence logic • Persistence Logic: is responsible for accessing persistence Data • If I’m using low level persistence logic in Business Logic (i.e High Level Logic) so I can not connect to all the Back end servers. • To avoid this problem we have to use another layer , keep the persistence logic in a separate object, that object is nothing but a Data Access Object (DAO). • • SO here DAO is a Design Pattern, Design Pattern which gives a solution for a problem. • (Example: I’m facing a problem, I will try to interact with a friend who is already faced the problem because he will have ready made solution for that problem, no need to waste my time to solve the problem, because already ready made solution (design pattern) is available
  • 54. What is Low Level Persistence Logic?
  • 55. Introducing DAO • When it comes into the project (enterprise application) we need to concentrate in optimizing the code, making the more reusable, and also testable. • The DAO is the most common pattern implemented into the enterprise applications.
  • 56. What is a Pattern? • Pattern is a three part document that describes the context (situation), reoccurring problem and the best solution for the problem in the given context (situation). • The software patterns are categorized into multiple type for convenience in learning and applying. • The design patterns is one of the category. This lists the patterns describing the problems related to design and development of the software applications
  • 57. THE DAO DESIGN PATTERN: • • As the title describes this is a design pattern • Context (situation): • We want to create enterprise Application with reasonable business logic having a requirement of accessing multiple (variety) of datastore and /or found that may have a requirement of migrating from one type of data store (database) to other. Easy to migrate between the different types of data stores. That is in my application I want to connect to LDAP to take credentials, same application I want to connect to File Systems to accept login details. • Problem: • We want to separate the low-level persistence (data access) logic from Business Logic. But this so this solution leaves a problem that is how do you separate in a best way? Thus this solution we kept in a problem. • Forces: (Why): • We want to have a proper responsibility division that is: • (a) improves the quality of the system. • (b) reduces the cost and time for the development • To enable unit testing, make the system more comfortable for testing. • Easy to migrate between the different types of data stores. • Solution: • Implement the low-level persistence logic into a separate object, exposing the data access operations through high-level API to the service layer.
  • 58. What is DAO ? • Ans: DAO is a design pattern that describes separating the low-level persistence logic from the business logic, implementing into a separate (independent) object. • • Note: this special object introduced implementing the DAO pattern is also refered as a DAO i.e: Data Access Object
  • 59.
  • 60. • From this discussion and the above architecture we understand JDBC is used for implementing the DAO in Java for accessing the tabular data store
  • 61. Use Case diagram of our project
  • 62. Implementing DAO Design Pattern in our project
  • 63. Implementing the Data Access Layer for ‘CreateEmployee’ use case of ‘Employee Management System (EMS). • For Example: • Implementing the Data Access Layer for ‘CreateEmployee’ use case of ‘Employee Management System (EMS). • • //EmployeeDAOI.java • package com.st.ems.dao; • public interface EmployeeDAOI • { • void save(int eno,String name, double sal, int dno); • //we will change this struture later • //we will add some more methods as we proceed • } • • • //EmployeeDAO.java • package com.st.ems.dao.jdbc; • import com.st.ems.dao.EmployeeDAOI; • import java.sql.*; • import java.util.*; • public class EmployeeDAO implements EmployeeDAOI • { • public void save(int eno, String name,double sal, int dno) • { • //this method is responsible for saving the given details into emp table • //to do: execute the following SQL • String sql="insert into emp values("+eno+",'"+name+",',"+sal+","+dno+")";
  • 64. • //how to execute? • //use JDBC • //Write this Connection con=null here only to make visible to all the blocks • Connection con=null;//null is necessary whn u r declaring as a local variable • try • { • //step 1.1 • String driverClassName="oracle.jdbc.driver.OracleDriver";//here we are using oracle driver • Class c=Class.forName(driverClassName); • Driver d=(Driver)c.newInstance(); • //step 1.2 • String jdbcUrl="jdbc:oracle:thin:@localhost:1521:XE"; • Properties p=new Properties(); • p.put("user","system"); • p.put("password","manager"); • //Connection con=null;//i can not use con ref variable in finally block as it is local to this • block • •
  • 65. • con=d.connect(jdbcUrl,p); • //step2 • Statement st=con.createStatement(); • //step3 • st.executeUpdate(sql); • • • }//end of try block • catch(Exception e) • { • e.printStackTrace(); • //to report the error, we will set run time error • throw new RuntimeException(e); • } • finally • { • try • { • //step 4: • con.close(); • • }//try • catch(Exception e){} • }//finally • • • }//save • }//class
  • 66. • /* now we are writing Tese case for DAO object [that is save()] for this we have to use JUNIT but • we are using main() for this application • */ • //EmployeeDAOTestCase.java • import com.st.ems.dao.jdbc.EmployeeDAO; • import com.st.ems.dao.EmployeeDAOI; • • • public class EmployeeDAOTestCase • { • private EmployeeDAOI edao; • public void testsave() • { • edao.save(102,"e102",20000,20); • System.out.println("Details saved"); • } • public static void main(String s[]) • { • EmployeeDAOTestCase test=new EmployeeDAOTestCase(); • test.edao=new EmployeeDAO(); • test.testsave();//here Driver object is created • //test.testsave();//here 2nd Driver object is created but one Driver object is enought to handle • //multiple request from diffrent clients, connections as it is a Thread -safe • } • }
  • 67. • /* • D:materialjava(E DRIVE)javaAdvJavajdbcDAO>javac -d . *.java • D:materialjava(E DRIVE)javaAdvJavajdbcDAO>D:materialjava(E • DRIVE)javaAdvJavajdbcDAO>set classpath=C:oraclexeappor • acleproduct10.2.0serverjdbclibojdbc14.jar;.; • D:materialjava(E DRIVE)javaAdvJavajdbcDAO>java EmployeeDAOTestCase • Details saved • */
  • 68.
  • 69. Q: is our DAO created efficient? • Ans: No, we need to multiple changes. Let us look into all of them one after the other • In the EmployeeDAO created earlier the save() method is programmed to create a new instance (object) of Driver class on every request, which is not effective. • Considering the following points with respect to the Driver: • The Driver object is Thread-safe means Driver object performs consistently even on concurrent requests from multiple threads • A single instance of Driver can be used to create multiple connections because it is Thread-safe. If we create the multiple instances of Driver class, unnecessarly garbage is stored into the memory, and performance becomes slow. • Considering these points a single instance of Driver is enough for an application per data base.