JAVA Lecture Breakup
1. About JAVA
2. Simple Java Programm Structure, Complilation & Execution, Java Virtual Machine,
3. Java Tokens.
4. Overview NetBeans IDE.
5. Comments, Command Line arguments
6. scope of variables, type, casting, operators & Expression
7. Class & objects, accessing class members
8. Decision Control Structures
9. Case Control Structures
9. Loop Control Structures
10. Methods overloading, Nesting of Methods, Constructor
11. Static Members
12. Inheritance : Extending a Class
13. Abstract Classes, Abstract Methods
14. Final Classes, Final Variable, Final Methods,
15. Inner Classes, Methods Overriding, this, super, Visibility Control
16. Interfaces
17. Arrays & Strings
18. Packages
19. Multi threaded Programming
20. Errors & Exceptions
21. Managing I/O Files
22. Java Collection Framework
23. Applet
24. AWT / Swing
25. Event Handling
Introduction, Event Source, Event Classes, Event Listeners, Adapter Classes.
26. JAVA Programm
Introduction
Java is an object oriented programming language developed by Sun Microsystems of USA in 1991. Originally name of Java is Oak Developed by James Gosling.
Java was invented for the development of software for cunsumer electronic devices like TVs, tosters, etc. The main aim had to make java simple, portable and reliable.
Java Authors: James , Arthur Van , and others.
Java Features
Features of Java are as follows:
1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
1. Compiled and Interpreted
Basically a computer language is either compiled or interpreted. Java comes together both these approach thus making Java a two-stage system.
Java compiler translates Java code to Bytecode instructions and Java Interpreter generate machine code that can be directly executed by machine that is running the Java program.
2. Platform Independent and portable
Java supports the feature portability. Java programs can be easily moved from one computer system to another and anywhere. Changes and upgrades in operating systems, processors and system resources will not force any alteration in Java programs. This is reason why Java has become a trendy language for programming on Internet which interconnects different kind of systems worldwide. Java certifies portability in two ways.
First way is, Java compiler generates the bytecode and that can be executed on any machine. Second way is, size of primitive data types are machine independent.
3. Object- oriented
Java is truly object-oriented language. In Java, almost everything is an Object. All program code and data exist in objects and classes. Java comes with an extensive set of classes; organize in packages that can be used in program by Inheritance. The object model in Java is trouble-free and easy to enlarge.
4. Robust and secure
Java is a most strong language which provides many securities to make certain reliable code. It is design as garbage –collected language, which helps the programmers virtually from all memory management problems. Java also includes the concept of exception handling, which detain serious errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use this language for programming on Internet.
The absence of pointers in Java ensures that programs cannot get right of entry to memory location without proper approval.
5. Distributed
Java is called as Distributed language for construct applications on networks which can contribute both data and programs. Java applications can open and access remote objects on Internet easily. That means multiple programmers at multiple remote locations to work together on single task.
6. Simple and small
Java is very small and simple language. Java does not use pointer and header files, goto statements, etc. It eliminates operator overloading and multiple inheritance.
7. Multithreaded and Interactive
Multithreaded means managing multiple tasks simultaneously. Java maintains multithreaded programs. That means we need not wait for the application to complete one task before starting next task. This feature is helpful for graphic applications.
8. High performance
Java performance is very extraordinary for an interpreted language, majorly due to the use of intermediate bytecode. Java architecture is also designed to reduce overheads during runtime. The incorporation of multithreading improves the execution speed of program.
9. Dynamic and Extensible
Java is also dynamic language. Java is capable of dynamically linking in new class, libraries, methods and objects. Java can also establish the type of class through the query building it possible to either dynamically link or abort the program, depending on the reply.
Java program is support functions written in other language such as C and C++, known as native methods.
Difference Between Java and C++
1. Java is true Object-oriented language. C++ is basically C with Object-oriented extension.
2 Java does not support operator overloading. C++ supports operator overloading.
3 It supports labels with loops and statement blocks It supports goto statement.
4 Java does not have template classes as in C++. C++ has template classes.
5 Java compiled into byte code for the Java Virtual Machine. The source code is independent on operating system. Source code can be written to be platform independent and written to take advantage of platform.C++ typically compiled into machine code.
6 Java does not support multiple inheritance of classes but it supports interface. C++ supports multiple inheritance of classes.
7 Runs in a protected virtual machine. Exposes low-level system facilities.
8 Java does not support global variable. Every variable should declare in class. C++ support global variable.
9 Java does not use pointer. C++ uses pointer.
10 It Strictly enforces an object oriented programming paradigm. It Allows both procedural programming and object-oriented programming.
11. There are no header files in Java. We have to use header file in C++.
Java Environment
Java environment includes a number of development tools, classes and methods. The development tools are part of the system known as Java Development Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known as the Application Programming Interface (API).
Java Development kit (JDK) – The JDK comes with a set of tools that are used for developing and running Java program.
It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javah(It is for java C header files)
6. Javadoc(It is for creating HTML document)
7. Jdb(It is Java debugger)
Java Standard Libraries Development (JSL) – The JSL consist a number classes or methods.
It includes:
1.lang - language utilities
2. utill - collection framework
3. io - input/ouput in java
4. applet - internet programming utilities
5. awt - windows heavyweight interface
6. swing - windows lightweight interface
Simple Java Program:
class FirstProgram
{
public static void main(String args[])
{
System.out.println(―This is my first program‖);
}
}
The file must be named ―FirstProgram.java‖ to equivalent the class name containing the main method. Java is case sensitive. This program defines a class called ―FirstProgram‖. A class is an object oriented term. It is designed to perform a specific task. A Java class is defined by its class name, an open curly brace, a list of methods and fields, and a close curly brace. The name of the class is made of alphabetical characters and digits without spaces, the first character must be alphabetical. The line ―public static void main (String [] args )‖ shows where the program will start running. The word main means that this is the main method –
The JVM starts running any program by executing this method first. The main method in FirstProgram.java‖ consists of a single statement
System.out.println("This is my first program");
The statement outputs the character between quotes to the console.
class
Definition: A class is a collection of objects of similar type. Once a class is defined, any number of objects can be produced which belong to that class.
Class Declaration
class classname
{
…
ClassBody
…
}
Objects are instances of the Class. Classes and Objects are very much related to each other. Without objects you can't use a class.
A general class declaration:
class name1
{
//public variable declaration
void methodname()
{
//body of method…
//Anything
}
}
use of dot operator
We can access the variables by using dot operator. Following program shows the use of dot operator.
Instance Variable
All variables are also known as instance variable. This is because of
the fact that each instance or object has its own copy of values for the variables.
Hence other use of the ―dot” operator is to initialize the value of variable for that
instance.
Note: using class & object concept
Q1. Write Java Code to determine simple interest. si=p*n*r/100
Q2. Write Java Code to determine area of circle.
Q3. Write Java Code to determine given number is even or odd.
Q4. Write Java Code to determine given number is prime or not prime.
Q5. Write Java Code to determine greates number among three variable.
Note: number taken by dynamically at run time
Q6. Write Java Code to take a number from keyboard & Display days of week.
1-Sunday 2-Monday ………….. 7-Saturday default – invalid number
Q7. Write Java Code to develop menu driven program.
1. Area of circle.
2. To determine input number is +ve or –ve
3. To swap any two number without using 3rd variable.
4. To display numeric number from 1 to 50.
Default – Invalid Choice.
Q8. Write Java Code to take any one number & find factorial of that number.
Q9. Write Java Code to take any one number & Display multiplication table of that number.
Q10. Write Java Code to display prime number on given range.
E.g1
class Area
{
double r;
void get(double n)
{
r=n;
}
double cal()
{
double a;
a=3.14*r*r;
return(a);
}
}
public class Areamain
{
public static void main(String[]args)
{
double r;
Area obj=new Area(); //obj is the object of Area
obj.get(5.63d);
r=obj.cal();
System.out.println("AREA OF CIRCLE : "+r);
}
}
E.g2
class MulTable
{
final static int ROWS = 20;
final static int COLUMNS = 20;
public static void main(String args[ ])
{
int product[][] = new int [ROWS][COLUMNS];
int row, column;
System.out.println("MULTIPLICATION TABLE");
System.out.println("");
int i,j;
for (i=10; i<ROWS; i++)
{
for (j=10; j<COLUMNS; j++)
{
product [i][j] = i*j;
System.out.print(" " +product[i][j]);
}
System.out.print("\n");
}
}
}
E.g3
class Rectangle
{
int length,width;
void getData(int x,int y) //method with signature
{
length = x;
width = y;
System.out.println("LENGTH = "+length);
System.out.println("WIDTH = "+width);
}
int rectArea () //return type method
{
int area = length * width;
return(area);
}
}
public class RectArea {
public static void main (String args[ ])
{
Rectangle rect = new Rectangle(); // rect1 is the object of Rectangle
rect.getData(85,95); //call
int result=rect.rectArea(); //call
System.out.println("Area of Rectangle =" +result);
}
}
Method overloading
Method overloading
is one of oop concept of java in which the name of method is same but number of
parameters or signatures, type of signatures & sequence of signatures must
be different.
public class Calc {
//method overloading
public int add(int x,int y)
{
return(x+y);
}
public int add(int x,int y ,int z)
{
return(x+y+z);
}
public float add(int x,float y)
{
return(x+y);
}
public float add(float x,int y)
{
return(x+y);
}
public static void main(String args[])
{
int r1,r2;
float r3,r4;
Calc cobj=new Calc();
r3=cobj.add(5.6f,7);
r4=cobj.add(8,7.67f);
r1=cobj.add(8,7,3);
r2=cobj.add(3,4);
System.out.println("result " +r1);
System.out.println("result " +r2);
System.out.println("result " +r3);
System.out.println("result " +r4);
}
}
Constructor
Constructor means
the name of class & method name is same.
Constructor have following properties:
1.
It does not have return type or even void.
2.
It automatically execute when object of class created.
3.
It always within public section.
Types of Constructor
1.
Default constructor : does not have signature or parameters.
2.
Parametrized constructor: have signature or parameters.
E.g of Constructor
public class Rect {
public void read() //method
{
System.out.println("Method");
}
public Rect() //Default constructor
{
System.out.println("Default Constructor");
}
public Rect(int l,int b) //parametrised constructor
{
System.out.println("parametrized Constructor");
System.out.println("Length : "+l);
System.out.println("Breadth : "+b);
}
public static void main(String[] args)
{
Rect r1=new Rect(); //default constructor
Rect r2=new Rect(34,56); //parametrised constructor
r1.read();
}
}
Constructor overloading
Name of constructor
is same but the type of signature or parameters, sequence of signature &
number of signature must be different.
class Sum
{
public Sum() //constructor
{
System.out.println("Default Constrcutor");
}
public Sum(int x,int y) //parametrized constructor
{
System.out.println("Parametrized Constrcutor");
System.out.println("x = "+x);
System.out.println("y = "+y);
}
public void write() //method
{
System.out.println("METHOD");
}
}
public class UseCons {
public static void main(String args[])
{
Sum obj1 =new Sum();
Sum obj2 =new Sum();
Sum obj3 =new Sum(5,6);
obj1.write();
// obj.Sum();
}
}
Static in Java
1.
Static variable : 0
2.
Static method : access only static
member
Static variable is
also called class variable and based on class level scope while non static
variable is also called instance variable and based on object level scope.
Default value of
static variable is zero.
Memory allocation of
static variable share by the multiple object of class while memory allocation
of non static variable is individual for each object of class.
Static method access
only static member without using object of class.
E.g1
public class UseStatic
{
int x; //non static or instance variable or object scope
static int y; //static or class scope or class variable
static void write()
{
System.out.println("Static Method");
}
void disp()
{
System.out.println("NonStatic Method");
}
public static void main(String args[])
{
int z=9; //local variable
y=78;
UseStatic obj=new UseStatic();
obj.x=56;
write();
obj.disp();
}
}
E.g2 of static
public class Op {
static int x;
Op()
{
x++;
System.out.println("Total Object = "+x);
}
public static void main(String args[])
{
Op obj1=new Op();
Op obj2=new Op();
Op obj3=new Op();
Op obj4=new Op();
System.out.println("x = "+x);
}
}
Access Specifies in JAVA
1. public – visible anywhere.
2. private – visible only within class of the same package.
3. protected – visible to within class as well as sub class of other package
Abstract in JAVA
An abstract class is a class that is declared as abstract. It may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclass.abstract class
it always act as super class.
it can’t instantiated (object can’t created).
must be inherits to sub class.
2 abstract method
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
1. it has declaration parts on super class & definition on sub class.
it must be override
E.g1
abstract class Fsuper
{
abstract void disp();
void run()
{
System.out.println("NORMAL METHOD");
}
}
class sub extends Fsuper
{
void disp()
{
System.out.println("ABSTRACT METHOD");
run();
}
}
public class Fprog {
public static void main(String[]args)
{
sub s=new sub();
s.disp();
}
}
Interface
Eg1:
interface Areac
{
final static float pi = 3.14F;
float compute(float x, float y);
}
class Rectangle implements Areac
{
public float compute(float x, float y)
{
return(x*y);
}
}
class Circle implements Areac
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Areac area;
area = rect;
System.out.println("Area of Rectengle = " + area.compute(10,20));
area = cir;
System.out.println("Area of Circle = " + area.compute(10,0));
}
}
Eg2:
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber()
{
System.out.println("Roll No : " + rollNumber);
}
}
class Test extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1 = m1;
part2 = m2;
}
void putMarks()
{
System.out.println("Marks obtained");
System.out.println("part1 = " + part1);
System.out.println("part2 = " +part2);
}
}
interface Sports
{
float sportWt = 6.0F;
void putWt();
}
class Results extends Test implements Sports
{
float total;
public void putWt()
{
System.out.println("Sports Wt = "+ total);
}
void display()
{
total = part1 + part2 + sportWt;
putNumber();
putMarks();
putWt();
System.out.println("Total score = "+ total);
}
}
class Hybrid
{
public static void main(String args[])
{
Results student1 = new Results();
student1.getNumber(1234);
student1.getMarks(27.5F, 33.0F);
student1.display();
}
}
Interfaces are similar to abstract classes. The differences are as follows:
1. All methods in an interface are abstract. Which means all methods must be empty; no code implemented.
2. In abstract class, the methods can have code/implementation within it. Atleast one method must be abstract.
3. All properties (data fields) in an interface are static final. Properties in an abstract class need not be static final.
4. Interfaces are implemented(implements keyword); Abstract classes are extended(extends keyword)
5. Class can extend only one abstract class; where as a class can implement multiple interfaces (multiple inheritance)
Method overriding
Method overriding
means the name of method & it’s signature is same in super class & sub
class. So the method of super class remains hide.
Super keyword used
to invoke the hide method of super class.
E.g
class A //super class
{
public void disp()
{
System.out.println("SUPER CLASS");
}
}
class B extends A
{
public void disp()
{
super.disp(); //it access method of super class
System.out.println("SUB CLASS");
}
}
public class Override {
public static void main(String args[])
{
B bobj=new B();
bobj.disp();
}
}
Final in JAVA
1. final variable - can't reintialized
e.g
final int x=5;
x=8;
2. final method - can not override
e.g.
class Fsuper
{
final void disp()
{
}
}
class sub extends Fsuper
{
void disp()
{
}
}
3. final class - cant't inherits to sub class.
e.g.
final class Fsuper
{
final void disp()
{
}
}
class sub extends Fsuper
{
}
Arrays in JAVA
1. One dimensional array: sequential array.
Eg1:
class Arrayp
{
Arrayp()
{
int arr[]={4,5,6,7,1,45,67,78};
int s=0;
System.out.println("ARRAY SIZE : "+arr.length);
for(int i=1;i<arr.length;i++)
{
s=s+arr[i];
System.out.println("values = "+arr[i]);
}
System.out.println("Total Sum values = "+s);
}
}
public class Arr {
public static void main(String args[])
{
Arrayp arr=new Arrayp();
}
}
Eg2:
import java.io.*;
public class Arr1 {
public static void main(String args[]) throws IOException
{
int arr[]=new int[5];
int l=arr.length;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(input);
// i/p in array
for(int i=0;i<l;i++)
{
System.out.println("ENTER ANY NUMBER : ");
arr[i]=Integer.parseInt(br.readLine());
}
// o/p in array
System.out.println("Array values ");
for(int i=0;i<l;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("\nReverse Array values ");
for(int i=l-1;i>=0;i--)
{
System.out.print(" "+arr[i]);
}
System.out.println("\n");
}
}
Eg3:
public class NumberSorting
{
public static void main(String args[])
{
int number[] = {5, 89,40,22, 80, 98,65, 71};
int n = number.length; //n is variable & int is datatype , number is array name
System.out.print("Given list :");
for(int i=0; i < n; i++)
{
System.out.print(" " + number[i]);
}
System.out.println(" ");
for (int i= 0; i < n; i++)
{
for (int j= i+1; j < n; j++)
{
if(number[i] > number[j])
{
int temp = number[i];
number[i] = number[j];
number[j] = temp;
}
}
}
System.out.print("Sorted list :");
for(int i=0;i < n; i++)
{
System.out.print(" " + number[i]);
}
System.out.println(" ");
}
}
2. Two Dimensional arrays: matrix format array.
Eg1:
public class Twodarr {
public static void main(String args[])
{
int arr[][]={
{3,4,5},
{4,6,7},
{2,9,8}
};
System.out.print("\n 3x3 MATRIX \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(" "+arr[i][j]);
}
System.out.print("\n");
}
}
}
Vector
Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework.
E.g1 of Vector
import java.util.*;
public class VectorValue
{
public static void main (String args[])
{
Vector list = new Vector();
int length = args.length;
list.addElement("india");
list.addElement("china");
list.addElement("australia");
list.addElement("america");
list.addElement("japan");
int size = list.size();
System.out.println("country name :" +list);
list.removeElementAt(3);
System.out.println("vector value" +list);
}
}
E.g2
class LanguageVector
{
public static void main(String args[])
{
Vector list = new Vector();
int length = args.length;
list.addElement("C++");
list.addElement("HTML");
list.addElement("DHTML");
list.insertElementAt("COBOL",2);
int size = list.size();
System.out.println("DESKTOP SIZE : "+list);
String listArray[] = new String[size];
list.copyInto(listArray);
System.out.println("List of Languages");
for(int i=0; i< size; i++)
{
System.out.println(listArray[i]);
}
System.out.println("vector value" +list);
list.removeAllElements();
System.out.println("vector value" +list);
}
}
Wrapper Class:
Collection framework like vector does not work with primitive data type, such types frame work, performed task with wrapper class.
Eg1
public class Wrapper
{
public static void main(String args[])
{
Integer IntVal = new Integer(77);
Float FloatVal = new Float(40);
Double DoubleVal = new Double(55);
Long LongVal = new Long(88);
int i= IntVal.intValue();
float f = FloatVal.floatValue();
long l = LongVal.longValue();
double d = DoubleVal.doubleValue();
System.out.println("i = "+i);
System.out.println("f = "+f);
System.out.println("d = "+d);
System.out.println("l = "+l);
}
}
E.g of Enumeration
public class Workingdays
{
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
public static void main(String args[])
{
for(Days d : Days.values())
{
weekend(d);
}
}
private static void weekend(Days d)
{
if(d.equals(Days.Sunday))
{
System.out.println("value = " + d + " is a Holiday");
}
else
{
System.out.println("value = " + d + " is a working day");
}
}
}
String in JAVA
String & String Buffer class supported in java for the String Manipulation task.
String object is immutable while String buffer object is mutable.
Eg1:
public class Sp1 {
public static void main(String[]args)
{
String s=new String("heLLo MuKeSh");
System.out.println("String Values : "+s);
System.out.println("Lowercase values : "+s.toLowerCase());
System.out.println("Uppercase values : "+s.toUpperCase());
System.out.println("Char at 7 : "+s.charAt(7));
System.out.println("substring 3 to 9 : "+s.substring(3,9));
System.out.println("Length : "+s.length());
System.out.println("Index of M : "+s.indexOf("M"));
}
}
Eg2:
import java.io.*;
public class Sp2 {
public static void main(String[]args) throws IOException
{
String s1,s2;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(input);
System.out.println("Enter First String values : ");
s1=br.readLine();
System.out.println("Enter Second String values : ");
s2=br.readLine();
System.out.println("First String values : "+s1);
System.out.println("Second String values : "+s2);
if(s1.compareTo(s2)==0)
{
System.out.println("BOTH ARE SAME");
}
else
{
System.out.println("BOTH ARE NOT SAME");
}
}
}
Eg3:
import java.io.*;
public class Sp3
{
public static void main(String[]args) throws IOException
{
String s1;
StringBuffer sb1;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(input);
System.out.println("Enter First String values : ");
s1=br.readLine();
sb1=new StringBuffer(s1);
System.out.println("Ur String values : "+sb1);
System.out.println("Ur Reverse String values : "+sb1.reverse());
}
}
Eg4:
import java.io.*;
public class sp2
{
public static void main(String args[])throws IOException
{
String s1;
StringBuffer str;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(input);
System.out.println("Enter First String values : ");
s1=br.readLine();
System.out.println("String values : "+s1);
str=new StringBuffer(s1);
str.reverse();
System.out.println("Reverse String values : "+str);
if(s1.compareTo(str.toString())==0)
{
System.out.println("IT IS PALENDROME");
}
else
{
System.out.println("NOT PALENDROME");
}
}
}
Errors & Exception in JAVA
Errors
An error means any mistake or wrong in the code of programm.
Errors
An error means any mistake or wrong in the code of programm.
1. Compile Time Error: Such types of error generated during compilation like syntax error, statement missing & many more.
2. Run time Error: Such types of Error generated during Execution time like number not divide by zero, out of bound, insufficient memory & many more.
3. Logical Error: such type of error generated from flow of program execution. Logical error detected by JVM. Like wrong output since he uses wrong formula.
Exception
An exception is run time error. All exception come under runtime error, but some exception detected at compiles time.
The exceptions that are checked at compile time by compiler are called checked exception while the exceptions that are checked at runtime by JVM are called unchecked exception.
The process which is responsible to resolve exception is called exception handling.
Exception Handling
A process which handle Exception. In java exception is handle by two ways:
1. Using try catch block.
2. Using throws clause
1. Using try catch block. :
try
{
// exeception code
}
Catch(Exception object)
{
//message
}
example
public class Arith {
public static void main(String args[])
{
try
{
int x=5,y=2,z;
System.out.println("x = "+x);
System.out.println("y = "+y);
z=x/y;
System.out.println("y = "+z);
}
catch(ArithmeticException e)
{
System.out.println("Error : "+e.getMessage());
}
}
}
2. Using throws clause
throws Exception name with method in the single line.
JSP
1. About JSP
2. JSP Architecture, JSP Life Cycle, JSP Program
3. Component of JSP
4. JSP Directives
5. JSP implicit object
6. JSP Form Processing
7. JSP Actions
8. Session Tracking or Management
9. Exception Handling in JSP
10. JSP Programm
SERVLET
1. About Servlet
2. Servlet Life Cycle, Servlet Architecture
3. Http Request & Http Response
4. Servlets Hierarchy, Differenence between Generic Servlet &
HttpServlet, Difference Between doget & dopost
5. Cookies
6. Session
7. Servlet Programm
JDBC
What is JDBC?
Java
Database Connectivity or JDBC for short is set of Java API's that enables the
developers to create platform and database independent applications in java.
The biggest advantage of programming in Java is its platform independence. An
appatelication written to access the MS Access database on Win 95/Win NT
platform can work on Linux against Oracle database, only by changing the name
of driver, provided none of the database calls it makes are vendor specific.
What are JDBC Drivers?
JDBC
Drivers are set of classes that enables the Java application to communicate
with databases. Java.sql that ships with JDK contains various classes for using
relational databases. But these classes do not provide any implementation, only
the behaviours are defined. The actual implementaions are done in third-party
drivers. Third party vendors implements the java.sql.Driver interface in their
database driver.
JDBC Drivers Types
JDBC Drivers Types
Sun
has defined four JDBC driver types. These are:
- Type 1: JDBC-ODBC Bridge Driver
The first type of JDBC dirver is JDBC-ODBC Bridge which provide JDBC access to any ODBC complaint databases through ODBC drivers. Sun's JDBC-ODBC bridge is example of type 1 driver. - Type 2: Native -API Partly - Java Driver
Type 2 drivers are developed using native code libraries, which were originally designed for accessing the database through C/C++. Here a thin code of Java wrap around the native code and converts JDBC commands to DBMS-specific native calls. - Type 3: JDBC-Net Pure Java Driver
Type 3 drivers are a three-tier solutions. This type of driver communicates to a middleware component which in turn connects to database and provide database connectivity. - Type 4: Native-Protocol Pure Java Driver
Type 4 drivers are entirely written in Java that communicate directly with vendor's database through socket connection. Here no translation or middleware layer, are required which improves performance tremendously.
Understanding Common SQL statements
The commonly used SQL statements are:1): Select
2): Insert
3): Update
4): Delete
SQL Select statement:
The SELECT statement is used to select data from a table.
Syntax: Select column_names FROM table_name;
The result from a SQL query is stored in a resultset. The SELECT statement has mainly three clauses.
1). Select
2.) From
3). Where
The Select specifies the table columns that are retrieved. The From clause tells from where the tables has been accessed. The Where clause specifies which tables are used. The Where clause is optional, if not used then all the table rows will be selected.
We can see that we have used semicolon at the end of the select statement. It is used to separate each SQL statement in database systems which helps us to execute more than one SQL statement in the same call to the server.
SQL INSERT Statement:
This statement allows you to insert a single or multiple records into the database. We can specify the name of the column in which we want to insert the data.
Syntax: Insert into table_name values (value1, value2..);
The Insert statement has mainly three clauses.
1). Insert: It specifies which table column has to be inserted in the table.
2). Into : It tells in which the data will be stored.
3). Values: In this we insert the values we have to insert.
We can also specify the columns for which we want to insert data.
The UPDATE Statement:
The Update statement is used to modify the data in the table. Whenever we want to update or delete a row then we use the Update statement.
The syntax is :
UPDATE table_name Set colunm_name = new_value WHERE column_name = some_name;
The Update statement has mainly three clauses.
1). UPDATE: It specifies which table column has to be updated.
2). Set: It sets the column in which the data has to be updated.
3). Where: It tells which tables are used.
SQL DELETE Statement:
This delete statement is used to delete rows in a table.
Systax:
DELETE FROM table_name WHERE column_name = some_name;
The Delete statement has following clauses.
1). Delete: It specifies which table column has to be deleted.
2). From: It tells from where the Table has been accessed.
3). Where: It tells which tables are used.
Introduction to java.sql package
This package provides the APIs for
accessing and processing data which is stored in the database especially
relational database by using the java programming language. It includes a
framework where we different drivers can be installed dynamically to access
different databases especially relational databases. This java.sql package contains API for the following :
1 Making a connection with a database with the help of DriverManager class
a) DriverManager class: It helps to make a connection with the driver.
b) SQLPermission class: It provides a permission when the code is running within a Security Manager, such as an applet. It attempts to set up a logging stream through the DriverManager class.
c) Driver interface : This interface is mainly used by the DriverManager class for registering and connecting drivers based on JDBC technology.
d). DriverPropertyInfo class : This class is generally not used by the general user.
2). Sending SQL Parameters to a database :
a). Statement interface: It is used to send basic SQL statements.
b). PreparedStatement interface: It is used to send prepared statements or derived SQL statements from the Statement object.
c). CallableStatement interface : This interface is used to call database stored procedures.
d). Connection interface : It provides methods for creating statements and managing their connections and properties.
e). Savepoint : It helps to make the savepoints in a transaction.
3). Updating and retrieving the results of a query:
a). ResultSet interface: This object maintains a cursor pointing to its current row of data. The cursor is initially positioned before the first row. The next method of the resultset interface moves the cursor to the next row and it will return false if there are no more rows in the ResultSet object. By default ResultSet object is not updatable and has a cursor that moves forward only.
4.) Providing Standard mappings for SQL types to classes and interfaces in Java Programming language.
a). Array interface: It provides the mapping for SQL Array.
b). Blob interface : It provides the mapping for SQL Blob.
c). Clob interface: It provides the mapping for SQL Clob.
d). Date class: It provides the mapping for SQL Date.
e). Ref interface: It provides the mapping for SQL Ref.
f). Struct interface: It provides the mapping for SQL Struct.
g). Time class: It provides the mapping for SQL Time.
h). Timestamp: It provides the mapping for SQL Timestamp.
i). Types: It provides the mapping for SQL types.
5). Metadata
a). DatabaseMetaData interface: It keeps the data about the data. It provides information about the database.
b). ResultSetMetaData: It gives the information about the columns of a ResultSet object.
c). ParameterMetaData: It gives the information about the parameters to the PreparedStatement commands.
6). Exceptions
a). SQLException: It is thrown by the mehods whenever there is a problem while accessing the data or any other things.
b). SQLWarning: This exception is thrown to indicate the warning.
c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch update are not executed successfully.
d). DataTruncation: It is thrown to indicate that the data may have been truncated.
7). Custom mapping an SQL user- defined type (UDT) to a class in the java programming language.
a). SQLData interface: It gives the mapping of a UDT to an intance of this class.
b). SQLInput interface: It gives the methods for reading UDT attributes from a stream.
c). SQLOutput: It gives the methods for writing UDT attributes back to a stream.
Driver Manager Class
The JDBC Driver ManagerThe JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. It's very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application. The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected.
The DriverManager class works between the user and the drivers. The task of the DriverManager class is to keep track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. It even keeps track of the driver login time limits and printing of log and tracing messages. This class is mainly useful for the simple application, the most frequently used method of this class is DriverManager.getConnetion(). We can know by the name of the method that this method establishes a connection to a database.
The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the DriverManager class by calling the method DriverManager.registerDriver().
By calling the Class.forName() method the driver class get automatically loaded. The driver is loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves automatically when their driver implementation class get loads.
This class has many methods. Some of the commonly used methods are given below:
1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class.
2. registerDriver(Driver driver) : It registers the driver with the DriverManager class.
3. getConnection(String url) : It tries to establish the connection to a given database URL.
4. getConnection(String url, Sting user, String password) : It tries to establish the connection to a given database URL.
5. getConnection(String url, Properties info) : It tries to establish the connection to a given database URL.
6. getDriver(String url) : It attempts to locate the driver by the given string.
7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class.
Understanding Data Source
The JDBC API provides the DataSource
interface as an alternative to the DriverManager for establishing the
connection. A DataSource object is the representation of database or the data
source in the Java programming language. DataSouce object is mostly preferred
over the DriverManager for establishing a connection to the database. DataSource object can be thought as a factory for making connections to the particular database that the DataSource instance represents.
DataSource has a set of properties that identify and describe the real world data source that it represents. The properties include information about the location of the database server, the network protocol use to communicate with the server the name of the database and so on.
DataSource object works with JNDI (Java Naming and Directory interface) naming service so application can use the JNDI API to access the DataSource object.
In short we can say that the DataSource interface is implemented to provide three kinds of connections:
1). Basic DataSource class
This class is provided by the driver vendor. It is used for portability and easy maintence.
2). To provide connection pooling.
It is provided by the application server vendor or driver vendor. It works with ConnectionPoolDataSource class provided by a driver vendor. Its advantage is portability, easy maintenence and increased performance.
3). To provide distributed transactions
This class works with an XADataSource class, which is provided by the driver vendor. Its advantages are easy maintenence, portability and ability to participate in distributed transactions.
Understanding Connection Object
A Connection object represents a
connection with a database. When we connect to a database by using connection
method, we create a Connection Object, which represents the connection to the
database. An application may have one or more than one connections with a
single database or many connections with the different databases also. We can use the Connection object for the following things:
1). It creates the Statement, PreparedStatement and CallableStatement objects for executing the SQL statements.
2). It helps us to Commit or roll back a jdbc transactionn.
3). If you want to know about the database or data source to which you are connected then the Connection object gathers information about the database or data source by the use of DatabaseMetaData.
4). It helps us to close the data source. The Connection.isClosed() method returns true only if the Connection.close() has been called. This method is used to close all the connection.
Firstly we need to to establish the connection with the database. This is done by using the method DriverManager.getConnection(). This method takes a string containing a URL. The DriverManager class, attempts to locate a driver that can connect to the database represented by the string URL. Whenever the getConnection() method is called the DriverManager class checks the list of all registered Driver classes that can connect to the database specified in the URL.
Syntax:
String url = "jdbc: odbc: makeConnection";
Connection con = DriverManager.getConnection(url, "userID", "password");
JDBC Steps – Basic steps in writing a
JDBC Application
his
section gives you brief description of JDBC Steps for making connection
with the database, executing the query and showing the data to the user. In
this application we have connected to the MySQL database and retrieved the
employee names from the database. Here are the JDBC Steps to be followed
while writing JDBC program:
- Loading Driver
- Establishing Connection
- Executing Statements
- Getting Results
- Closing Database Connection
Before
explaining you the JDBC Steps for making connection to the database and
retrieving the employee from the tables, we will provide you the structure of
the database and sample data.
Understanding the JDBC Architecture
JDBC is an API specification developed by Sun
Microsystems that defines a uniform interface for accessing various
relational databases. JDBC is a core part of the Java platform and is included
in the standard JDK distribution.
The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as:
The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as:
- Database connections
- SQL statements
- Result Set
- Database metadata
- Prepared statements
- Binary Large Objects (BLOBs)
- Character Large Objects (CLOBs)
- Callable statements
- Database drivers
- Driver manager
The
JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager
ensures that the correct driver is used to access each data source. The Driver
Manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases. The location of the driver manager with
respect to the JDBC drivers and the servlet is shown in Figure 1.
Layers of the JDBC Architecture
Layers of the JDBC Architecture
A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database. This translation layer provides JDBC applications with database independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications required. There are four distinct types of JDBC drivers.
Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java statements are converted to a jdbc statements. JDBC statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed by the database. This driver has serious limitation for many applications. (See Figure 2.)
Type 1 JDBC Architecture
Type 2 Java to Native API. Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database library API. This driver converts the JDBC calls into a database specific call for databases such as SQL, ORACLE etc. This driver communicates directly with the database server. It requires some native code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers require native database client libraries to be installed and configured on the client machine. (See Figure 3.)
Type 2 JDBC Architecture
Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are pure Java drivers that use a proprietary network protocol to communicate with JDBC middleware on the server. The middleware then translates the network protocol to database-specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can connect to many different databases on the back end. Type 3 drivers can be deployed over the Internet without client installation. (See Figure 4.)
Java-------> JDBC statements------> SQL statements ------> databases.
Type 3 JDBC Architecture
Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation. One drawback to Type 4 drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes, you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of charge from the database manufacturer). However, because Type drivers communicate directly with the database engine rather than through middleware or a native library, they are usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL statements.
(See
Figure 5.)
Type 4 JDBC Architecture
Type 4 JDBC Architecture
So, you may be asking yourself, "Which is the right type of driver for your application?" Well, that depends on the requirements of your particular project. If you do not have the opportunity or inclination to install and configure software on each client, you can rule out Type 1 and Type 2 drivers.
However, if the cost of Type 3 or Type 4 drivers is prohibitive, Type 1 and type 2 drivers may become more attractive because they are usually available free of charge. Price aside, the debate will often boil down to whether to use Type 3 or Type 4 driver for a particular application. In this case, you may need to weigh the benefits of flexibility and interoperability against performance. Type 3 drivers offer your application the ability to transparently access different types of databases, while Type 4 drivers usually exhibit better performance and, like Type 1 and Type 2 drivers, may be available free if charge from the database manufacturer.
JDBC Driver and Its Types
JDBC Driver Manager
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.
This is a very important class. Its main purpose is to provide a means of managing the different types of JDBC database driver. On running an application, it is the DriverManager's responsibility to load all the drivers found in the system property jdbc. drivers. For example, this is where the driver for the Oracle database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at runtime which is not included in jdbc.drivers. When opening a connection to a database it is the DriverManager' s role to choose the most appropriate driver from the previously loaded drivers.
The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor.
A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver.
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.
This is a very important class. Its main purpose is to provide a means of managing the different types of JDBC database driver. On running an application, it is the DriverManager's responsibility to load all the drivers found in the system property jdbc. drivers. For example, this is where the driver for the Oracle database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at runtime which is not included in jdbc.drivers. When opening a connection to a database it is the DriverManager' s role to choose the most appropriate driver from the previously loaded drivers.
The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor.
A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver.
JDBC Driver
This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.
Types of JDBC drivers
This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.
There are four types of JDBC drivers known as:
This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.
Types of JDBC drivers
This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.
There are four types of JDBC drivers known as:
- JDBC-ODBC bridge plus ODBC driver, also called Type 1.
- Native-API, partly Java driver, also called Type 2.
- JDBC-Net, pure Java driver, also called Type 3.
- Native-protocol, pure Java driver, also called Type 4.
Type 1 Driver- the JDBC-ODBC bridge
The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.
The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver. Hence the use of this driver is discouraged if the alternative of a pure-Java driver is available.
Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.
A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.
Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS) platforms. The Java Native Interface (JNI) is used to call ODBC functions from the JDBC driver.
A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be a serious drawback for a production application. Type 1 drivers cannot be used in an applet since applets cannot load native code.
Functions:
The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.
The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver. Hence the use of this driver is discouraged if the alternative of a pure-Java driver is available.
Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.
A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.
Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS) platforms. The Java Native Interface (JNI) is used to call ODBC functions from the JDBC driver.
A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be a serious drawback for a production application. Type 1 drivers cannot be used in an applet since applets cannot load native code.
Functions:
- Translates query obtained by JDBC into corresponding ODBC
query, which is then handled by the ODBC driver.
- Sun provides a JDBC-ODBC Bridge driver.
sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and
is closed
source. - Client -> JDBC Driver -> ODBC Driver -> Database
- There is some overhead associated with the translation work to go
from JDBC to ODBC.
Advantages:
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages:
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages:
- Performance overhead since the calls have to go through the JDBC
overhead bridge to the ODBC driver, then to the native database
connectivity interface.
- The ODBC driver needs to be installed on the client machine.
- Considering the client-side software needed, this might not be
suitable for applets.
Type 2 Driver - the Native-API Driver
The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.
The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls.
The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, being
a full-Java implementation, is preferred over this driver.
A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
However the type 2 driver provides more functionality and performance than the type 1 driver as it does not have the overhead of the additional ODBC function calls.
Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers.
Type 2 drivers need native binary code installed and configured to work. A Type 2 driver also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load native code. A Type 2 JDBC driver may require some Database Management System (DBMS) networking software to be installed.
The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.
Functions:
The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.
The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls.
The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, being
a full-Java implementation, is preferred over this driver.
A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
However the type 2 driver provides more functionality and performance than the type 1 driver as it does not have the overhead of the additional ODBC function calls.
Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers.
Type 2 drivers need native binary code installed and configured to work. A Type 2 driver also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load native code. A Type 2 JDBC driver may require some Database Management System (DBMS) networking software to be installed.
The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.
Functions:
- This type of driver converts JDBC calls into calls to the client
API for that database.
- Client -> JDBC Driver -> Vendor Client DB Library ->
Database
Advantage
Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
- The vendor client library needs to be installed on the client
machine.
- Cannot be used in internet due the client side software needed.
- Not all databases give the client side library.
Type 3 driver - the Network-Protocol Driver
The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.
The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.
This
differs from the type 4 driver in that the protocol conversion logic resides
not at the client, but in the middle-tier. However, like type 4 drivers, the
type 3 driver is written entirely in Java.
The
same driver can be used for multiple databases. It depends on the number of
databases the middleware has been configured to support. The type 3 driver is
platform-independent as the platform-related differences are taken care by the
middleware. Also, making use of the middleware provides additional advantages
of security and firewall access.
A
net-protocol fully Java technology-enabled driver translates JDBC API calls
into a DBMS-independent net protocol which is then translated to a DBMS
protocol by a server. This net server middleware is able to connect all of its
Java technology-based clients to many different databases. The specific
protocol used depends on the vendor. In general, this is the most flexible
JDBC API alternative. It is likely that all vendors of this solution will
provide products suitable for Intranet use. In order for these products to also
support Internet access they must handle the additional requirements for
security, access through firewalls, etc., that the Web imposes. Several vendors
are adding JDBC technology-based drivers to their existing database
middleware products.
These
drivers use a networking protocol and middleware to communicate with a server.
The server then translates the protocol to DBMS function calls specific to
DBMS.
Type
3 JDBC drivers are the most flexible JDBC solution because they do not require
any native binary code on the client. A Type 3 driver does not need any
client installation.
Functions:
Functions:
- Follows a three tier communication approach.
- Can interface to multiple databases - Not vendor specific.
- The JDBC Client driver written in java, communicates with a
middleware-net-server using a database independent protocol, and
then this net server translates this request into database commands for
that database.
- Thus the client driver to middleware communication is database
independent.
- Client -> JDBC Driver -> Middleware-Net Server -> Any
Database
Advantages
- Since the communication between client and the middleware server is
database independent, there is no need for the vendor db library on
the client machine. Also the client to middleware need'nt be changed for a
new database.
- The Middleware Server (Can be a full fledged J2EE Application
server) can provide typical middleware services like caching
(connections, query results, and so on), load balancing, logging, auditing
etc..
- eg. for the above include jdbc driver features in Weblogic.
- Can be used in internet since there is no client side software
needed.
- At client side a single driver can handle any database.(It works
provided the middlware supports that database!!)
Disadvantages
- Requires database-specific coding to be done in the middle tier.
- An extra layer added may result in a time-bottleneck. But
typically this is overcome by providing efficient middleware
services described above.
Type 4 - the Native-Protocol Driver
The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol.
The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 1 and 2 drivers, it does not need associated software to work.
A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
As the database protocol is vendor-specific, separate drivers, usually vendor-supplied, need to be used to connect to the database.
A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the protocols are usually proprietary, DBMS vendors are generally the only companies providing a Type 4 JDBC driver.
Type 4 drivers are all Java drivers. This means that there is no client installation or configuration. However, a Type 4 driver may not be suitable for some applications if the underlying protocol does not handle issues such as security and network connectivity well.
The IBM Toolbox for Java JDBC driver is a Type 4 JDBC driver, indicating that the API is a pure Java networking protocol driver.
Functions
The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol.
The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 1 and 2 drivers, it does not need associated software to work.
A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
As the database protocol is vendor-specific, separate drivers, usually vendor-supplied, need to be used to connect to the database.
A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the protocols are usually proprietary, DBMS vendors are generally the only companies providing a Type 4 JDBC driver.
Type 4 drivers are all Java drivers. This means that there is no client installation or configuration. However, a Type 4 driver may not be suitable for some applications if the underlying protocol does not handle issues such as security and network connectivity well.
The IBM Toolbox for Java JDBC driver is a Type 4 JDBC driver, indicating that the API is a pure Java networking protocol driver.
Functions
- Type 4 drivers are entirely written in Java that communicate
directly with a vendor's database through socket connections. No
translation or middleware layers, are required, improving performance.
- The driver converts JDBC calls into the vendor-specific database
protocol so that client applications can communicate directly with the
database server.
- Completely implemented in Java to achieve platform independence.
- e.g include the widely used Oracle thin driver -
oracle.jdbc.driver. OracleDriver which connect to
jdbc:oracle:thin URL format.
- Client Machine -> Native protocol JDBC Driver -> Database
server
Advantages
These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved.
Disadvantage
At client side, a separate driver is needed for each database.
These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved.
Disadvantage
At client side, a separate driver is needed for each database.
JDBC Versions
1). The JDBC 1.0 API.2). The JDBC 1.2 API.
3). The JDBC 2.0 Optional Package API.
4). The JDBC 2.1 core API.
5) The JDBC 3.0 API.
6) The JDBC 4.0 API.
Features of JDBC 1.0 API
The JDBC 1.0 API was the first officially JDBC API launched consists of the following java classes and interfaces that you can open connections to particular databases.
This version includes a completely redesigned administration console with an enhanced graphical interface to manage and monitor distributed virtual databases.
Features of JDBC 1.2 API
1). It supports Updatabale ResultSets.
2). The DatabaseMetaData code has been refactored to provide more transparency with regard to the underlying database engine.
3) New pass through schedulers for increased performance.
Features of The JDBC 2.0 Optional Pacakage API
1). The use of DataSource interface for making a connection.
2). Use of JNDI to specify and obtain database connections.
3). It allows us to use Pooled connections, that is we can reuse the connections.
4). In this version the distrbuted transactions is possible.
5). It provides a way of handling and passing data using Rowset technology.
Features of the JDBC 2.1 core API.
1). Scroll forward and backward in a result set or has the ability to move to a specific row.
2). Instead of using SQL commands, we can make updates to a database tables using methods in the Java programming language
3). We can use multiple SQL statements in a a database as a unit, or batch.
4). It uses the SQL3 datatypes as column values. SQL3 types are Blob, Clob, Array, Structured type, Ref.
5). Increased support for storing persistent objects in the java programming language.
6). Supports for time zones in Date, Time, and Timestamp values.
7). Full precision for java.math.BigDecimal values.
Features of JDBC 3.0 API
1). Reusabilty of prepared statements by connection pools.
2). In this version there is number of properties defined for the ConnectionPoolDataSource. These properties can be used to describe how the PooledConnection objects created by DataSource objects should be pooled.
3) A new concept has been added to this API is of savepoints.
4). Retrieval of parameter metadata.
5). It has added a means of retrieving values from columns containing automatically generated values.
6). Added a new data type i.e. java.sql.BOOLEAN.
7). Passing parameters to CallableStatement.
8). The data in the Blob and Clob can be altered.
9). DatabaseMetaData API has been added.
Features of JDBC 4.0 :
1). Auto- loading of JDBC driver class.
2). Connection management enhancements.
3.) Support for RowId SAL type.
4). SQL exception handling enhancements.
5). DataSet implementation of SQl using Annotations.
6). SQL XML support
New Features in JDBC 4.0
ava database connectivity (JDBC) is the
Java Soft specification of the API. It allows Application Programs to interact
with the Database to access the Relational Data. Typically the JDBC API
consists of a set of interfaces and classes written in the Java programming
language. The applications can be written to connect to databases using these
standard interfaces and classes and also to process the results by sending
queries written in SQL. Furthermore the back-end Database session can be
connected by JDBC API which can execute the Queries to get the Results.Some of the new set of features which come along with Mustang is JDBC 4.0 are:
1.
No need for
Class.forName("DriverName")
2.
Changes in
Connection and Statement Interface
3.
Better Pools
4.
Using
ResultSet Becomes More Flexible
5.
More APIs
Become Available
The three most important features of Driver
and Connection Management in JDBC are described below with some new
features and enhancements. 1. Getting Connected Becomes Easier
This is one of the most important feature in JDBC that has relieved the developers from loading the driver explicitly. Exactly, you got it right, no need to explicitly load the driver by calling Class.forName anymore. So from now on don't bother to load the driver because the DriverManager will automatically load the driver found in the application CLASSPATH while your application tries to connect the database for the first time. However it is still preferred to create an appropriate DataSource object to retrieve a connection. Since the properties of data source instance can be modified which allows portability and transparency, there is no need to modify any application code to connect to a different database instance. Hence to retrieve a connection there is no need to change any application code to connect to a different database instance that requires loading a different driver.
For example: Earlier the programmers used to manually load the drivers before making any Database Calls. The code which was used by the programmers is:
Class.forName("FullyQualifiedNameOfTheDriverClass");
The disadvantage is that the code will be changed if the Database Driver vendor wants to change the class name. Now this problem doesn't persist anymore. With the help of Service Provider Mechanism available from Java 5, the Driver will be Loaded Automatically by the JVM provided that the Jar files corresponding to the Driver Class are in the appropriate class path.
To understand this mechanism consider two entities, one is the service which contains a set of interfaces and the other entity is the provider who gives a well-defined Implementation for the Service. Now to maintain a directory structure, this service is packaged as a Jar by the provider. The structure of a directory is:
\\META-INF\\services\\FullNameOfTheService
After maintaining the directory structure, if the JDBC Driver Provider wants to make his implementation as a Service then he has to maintain the file name along with the directory structure as,
\\META-INF\\services\\java.sql.Driver
Rememeber the file should only contain one entry that is the Name of the Provider Class. The function of this entry is to implement the Driver. Also the name of the file is java.sql.Driver in the above code. For instance the content of the file in My SQL would be,
File - Java.sql.Driver
com.mysql.jdbc.Driver # Class name of the Driver
Hence any Java program will automatically load the JDBC driver by the procedure. Moreover if the application class-path contains multiple drivers then the preference will be given to the first matching driver only ignoring the rest of the drivers.
2. Using ResultSet Becomes More Flexible
Several important features of ResultSet interfaces hierarchy are described below:
1.
The
ResultSet provided by the RowSet sub-interface is scrollable, updateable,
and offline-editable . The JDBC programming has become much more easier and
flexible due to the current version's support for the SQLXML data type
along with these features.
2.
Another
feature of the ResultSet is the WebRowSet sub-interface. This interface
provides the ability to read data from database tables. Moreover it is used to serialize
the data to an XML document, and deserialize from XML back to result
set.
JDBC-ODBC Connectivity
The code
illustrates an example from JDBC-ODBC Connectivity. The code helps you in
retrieve the name and size of the column. To understand this example we
have a class JdbcOdbcConnectivity ,the class include a main method ( )
follows a list of step in it -
Importing a package java.sql,provides you a network interface for the
interaction between front-end application in java and database in the backend.
The first step inside the main method ( ) is to load a driver by calling class.forName
( ) by accepting driver class as argument.
DriverManager.getConnection ( ) :The Driver Manager call getConnection ( )
returns you an object of connection class. This method is used to built a
connection between url and database. The Connection object call createStatement
( ),this return you a sql object to send and execute SQL Statements in
database.
executeQuery ( ) : This method return you a record set from a table
using select query in sql.The obtained record set is stored in result set.
get Metadata ( ) : This method return you the property of the column's data
type, size, the methods, properties, and parameters of a component associated
with object in an application.
get ColumnCount ( ): This method return you the number of column in a
result set.
Finally
the println print the column name
get Column Display Size ( ): This method return you the designated column's
normal maximum width in characters.
In case
there exists an exception in try block, the catch block check and handle. the
exception.
JdbcOdbcConnectivity.java
import java.sql.*;
public class JdbcOdbcConnectivity {
static private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
static private final String connection = "jdbc:odbc:emp";
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
ResultSetMetaData metaData = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(connection);
st = con.createStatement();
String sql = "select * from Employees";
rs = st.executeQuery(sql);
metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " +
metaData.getTableName(rowCount));
System.out.println("Field\t\t" +"Type");
System.out.println("--------------------");
for (int i = 0; i < rowCount; i++) {
System.out.print( metaData.getColumnName(i+1)+"\t");
System.out.println(" "+metaData.getColumnDisplaySize(i+1));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
public class JdbcOdbcConnectivity {
static private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
static private final String connection = "jdbc:odbc:emp";
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
ResultSetMetaData metaData = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(connection);
st = con.createStatement();
String sql = "select * from Employees";
rs = st.executeQuery(sql);
metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " +
metaData.getTableName(rowCount));
System.out.println("Field\t\t" +"Type");
System.out.println("--------------------");
for (int i = 0; i < rowCount; i++) {
System.out.print( metaData.getColumnName(i+1)+"\t");
System.out.println(" "+metaData.getColumnDisplaySize(i+1));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
JDBC-ODBC Connection
JDBC-ODBC
Connection is a JDBC driver that translates the operation in JDBC into
ODBC. For ODBC,it is a normal java application program. This bridge provides
JDBC for database in which an ODBC driver is available. The bridge is
represented as sun.jdbc.odbc.The Java contain a defined package and its library
to access ODBC.
Understand with Example
In this
Tutorial we help you in explaining JDBC Odbc Connection in Java. The code
explains you a how creation and closing of connection is done. For this code we
have a JdbcOdbc Connection class. The class contains a main method,
that include a list of steps as follow -
Loading a driver is the first step to be done inside the try block of main
method ( ) by calling a Class.forName ( ),this class accept a
"sun.jdbc.odbc.jdbcodbc Driver" as argument.
DriverManager.getConnection ( ) : This establish or built a connection
between url and emp table in the database.
The
print print the "New Connection Create..."..The Connection object
call a close ( ),return you the connection is closed. The println show
the "Connection closed"
In case
the exception exists in a try block, the subsequent catch block check and
handle the exception.
JdbcOdbcConnection.java
import java.sql.*;
public class JdbcOdbcConnection {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:emp");
System.out.println("New Connection Create ....");
con.close();
System.out.println("Connection closed");
} catch (Exception e) {
System.out.println(e);
}
}
}
public class JdbcOdbcConnection {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:emp");
System.out.println("New Connection Create ....");
con.close();
System.out.println("Connection closed");
} catch (Exception e) {
System.out.println(e);
}
}
}
JDBC Nested Resultset
The JDBC
Nested Result Set is the simplest join algorithm. In this case for each
tuple in the outer join relation, the entire inner join is scanned and the
tuple matches the join condition are finally added to the result set.
Understand with Example
In this
Tutorial we want to describe you a code that helps in understanding JDBC Nested
Result Set. The code include a class JDBC Nested Result Set, Inside the class
we have a main method, follow the list of steps -
Import a package java.sql provides you a network interface, that
enables to communicate between front end and back end.
Loading a driver by making a call class.forName ( ),that accept driver
class as argument.
DriverManager.getConnection ( ) : This provides you to established a
connection between url and database.
createStatement
( ) : The create Statement is used to obtain sql object. This object is
used to send and execute sql queries in backend of the database.
executeQuery ( ) :This method is used to retrieve the record set from a
table and store the record set in a result set. The select statement is used
for this method.
next
( ) : This method is used to return the next element in the series.
getString ( ) : This method retrieve the value of the specific column
in the current row of result set object as string representation.
Finally
the println print the ID,Name,Class in the output. In the same way if the tuple
in the result set 1 matches with the tuple result set 2,The output will
be printed In case there is an exception in try block, the catch
block caught and handle the exception.
JdbcNestedResultset.java
import java.sql.*;
public class JdbcNestedResultset {
public static void main(String args[]) {
Connection con = null;
Statement st1 = null;
Statement st2 = null;
ResultSet rs1 = null;
ResultSet rs2 = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
st1 = con.createStatement();
st2 = con.createStatement();
String sql = "Select * from stu";
rs1 = st1.executeQuery(sql);
System.out.println("Id\tName\tClass\tLibno");
while (rs1.next()) {
String id = rs1.getString("id");
System.out.print(id + "\t");
System.out.print(rs1.getString("name") + "\t");
System.out.print(rs1.getString("class") + "\t");
rs2 = st2.executeQuery("select * from lib where id ='" + id + "'");
while (rs2.next()) {
System.out.println(rs2.getString("libno") + "\t");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class JdbcNestedResultset {
public static void main(String args[]) {
Connection con = null;
Statement st1 = null;
Statement st2 = null;
ResultSet rs1 = null;
ResultSet rs2 = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
st1 = con.createStatement();
st2 = con.createStatement();
String sql = "Select * from stu";
rs1 = st1.executeQuery(sql);
System.out.println("Id\tName\tClass\tLibno");
while (rs1.next()) {
String id = rs1.getString("id");
System.out.print(id + "\t");
System.out.print(rs1.getString("name") + "\t");
System.out.print(rs1.getString("class") + "\t");
rs2 = st2.executeQuery("select * from lib where id ='" + id + "'");
while (rs2.next()) {
System.out.println(rs2.getString("libno") + "\t");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Understand with Example
The code illustrates you an example from JDBC Prepared Statement Close. In this program, the code describe how the Jdbc Prepared statement is closed. For this we have a class Jdbc Prepared statement, that include the main method and the list of steps to be carried out are as follow-
Before implementing class, import a Java.sql package, that contains a set of classes defining network interface for interaction between java front-end application and database.
Inside the main( ) method, we have a try block includes the loading a driver by calling a class.forName( ) and accept driver class as argument.
The DriverManager.getConnection ( ) return you a connection object. This object return you a built in connection between url and database.
prepareStatement ( ) :This method is used to execute the same statement object many times, This reduces the execution time for statement.
executeQuery( ): This method is used to retrieve the record set from a table. The select statement return you a result set .
next ( ) : This method return you the next elements in the series.
getString ( ):The Result Set call a getString ( ),returns you a string object representation
close ( ) :The prepared statement object call close ( ),that close the connection between url and database.
Finally the print ln print the Id,Name respectively from the result set as output.
In case there is an exception in try block, The catch block caught and handle the exception.
import
java.sql.*;
public class
JdbcPreparedstatementClose {
public static void
main(String args[]) {
Connection con =
null
;
PreparedStatement pst =
null
;
ResultSet rs =
null
;
String url =
"jdbc:mysql://localhost:3306/"
;
String db =
"komal"
;
String driver =
"com.mysql.jdbc.Driver"
;
String user =
"root"
;
String pass =
"root"
;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
pst = con.prepareStatement(
"select * from stu"
);
rs = pst.executeQuery();
System.out.println(
"Id\tName\tClass"
);
while
(rs.next()) {
System.out.print(rs.getString(
1
) +
"\t"
);
System.out.print(rs.getString(
2
) +
"\t "
);
System.out.println(rs.getString(
3
));
}
rs.close();
pst.close();
con.close();
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
JDBC Prepared Statement Insert
The Tutorial illustrates a program in JDBC
Prepared Statement Insert. In this Tutorial the code describe the include
a class JdbcPreparedstatementInsert, Inside the class we have a main method
follows the list of steps as follow -
Importing
a java.sql provides you a network interface that enables you to communicate
between front end application in java and database in backend.
Loading a
driver inside the try block by calling a class.forName ( ),that accepts a
driver class as argument.
DriverManager.getConnection
( ) - The method enables you to built a connection between url and database.
In the
given below code, we declare String variable sql,that is used to hold the
insert value into the employees table.
prepare
Statement ( ) - Unlike create Statement, the prepare Statement is used to
execute the same statement object, if it is repeated again. Normally this
reduces the time of execution to execute the code.
set
String ( ) - This is a method defined in prepared Statement class, When
you want to substitute a question mark place holder in code, we use set XXX,In
case we want to substitute a question mark place holder by string ,then we
write set String( ).
execute
Update ( ) - This method return you a integer value show you the number of rows
inserted in a table. This also indicates a numbers of rows affected in the
table.
execute
Query ( ) - This method return you the result set ,that store the value
of record set. The select sql statement is used to retrieve the record from
table in database.
next ( )
- This method is used to retrieve the next series element in the result set.
Finally
the Print ln show you the output as specified below the code
In case
the exception exists in try block, the catch block caught and handle the
exception.
JdbcPreparedstatementInsert.java
import java.sql.*;
public class JdbcPreparedstatementInsert {
static private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
static private final String connection = "jdbc:odbc:emp";
public static void main(String args[]) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(connection);
con.setAutoCommit(false);
String sql = "insert into Employees (FirstName,LastName) values(?,?)";
pst = con.prepareStatement(sql);
pst.setString(1, "Girish");
pst.setString(2, "tewari");
pst.executeUpdate();
pst.close();
sql = "select * from Employees";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
System.out.print(rs.getString(1) + "\t");
System.out.print(rs.getString(2) + "\t");
System.out.println(rs.getString(3));
}
rs.close();
pst.close();
con.close();
} catch (Exception e) {
}
}
}
JDBC Prepared Statement Update
Understand with Example
The
Tutorial illustrates a code that help you in understanding JDBC Prepared
Statement Update. The code include a class Jdbc Prepared Statement, this class
include a main method ( ), Inside the main method we have a list of steps -
Importing
a package java.sql - This package provides you a network interface, that
enables you to communicate between front end application -back end. Loading a
driver by calling a class.forName ( ),that accept a driver class as
argument.
DriverManager.get
Connection ( ) -The Driver Manager call a getConnection ( ) method,
return you a connection object, built a connection between url and database.
The
connection object call a prepareStatement ( ),that is used to update the
table stu using where clause, specify the name of record to be updated at
runtime. The set String XXX return you a set value in the place of question
mark holder. The executeQuery ( ) return you the record set from a
updated table in the database.
Finally the println print the updated table from the database in output. The
catch block caught the exception in try block.
JdbcPreparedstatementUpdate.java
import java.sql.*;
public class JdbcPreparedstatementUpdate {
public static void main(String args[]) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
pst = con.prepareStatement("update stu set class=? where id =?");
pst.setString(1, "11");
pst.setString(2, "1");
pst.executeUpdate();
pst = con.prepareStatement("select * from stu");
rs = pst.executeQuery();
System.out.println("Id\tName\tClass");
while (rs.next()) {
System.out.print(rs.getString(1) + "\t");
System.out.print(rs.getString(2) + "\t ");
System.out.println(rs.getString(3));
}
rs.close();
pst.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
//connection through Type 1: JDBC-ODBC Bridge Driver
package Conn;
import java.awt.Insets;
import java.sql.*;
class DbIns {
Statement st;
Connection con;
String inqry;
String path;
public void insert()
{
try
{
path="jdbc:odbc:sqldsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(path);
inqry="insert into stud(rno,name,course) values(102,'kumar','BCA')";
st=con.createStatement();
st.execute(inqry);
con.close();
System.out.println("INSERTION DONE..");
}
catch(Exception e)
{
System.out.println("Error = "+e.getLocalizedMessage());
}
}
}
public class DbInsert {
public static void main(String[] args) {
DbIns dobj=new DbIns();
dobj.insert();
}
}
Comments
Post a Comment