Professional Documents
Culture Documents
Sun micro system as released JSE API. This is a public API released by sun micro system.
26
Once in the public API is released any body can provide the implementation. We call the
implementation has software, from the above diagram we have under studied that the
java a software released from different companies like IBM, BEA, SUN micro and etc.
All these companies have provided the implementations to all the classes and interfaces
released by sun micro system company.
They are so many disadvantages to store the data into file system. They are
File system does not provide security.
There is limit on the size of the files.
If we store the data into file the redundant data will be store.
We can resolve this entire problem by using data base servers only.
JDBC API is used if a java application want interact with database server.
There are so many database servers are available in the market. Some of them all
Oracle, MYSQL, SAP, IBMDB2, POINT database server and etc.
When ever we purchase any database server we get two different software’s
they are Database Server Program(S/W)
Database Client Program(S/W)
We using java application instead of oracle client program this is because by using oracle
client program. If we want to request the server the client is suppose to type the SQL
queries and sent the request to the server. But when we use a java application to send
the request to the server, user no need to generate SQL queries. When the user
interacts which GUI and the client click on the button the java application generate the
queries and send to server.
A ‘C’ program’s would like communicate with database server. If two programs would
like communicate each other they must use same protocol. If they use different protocol
they will not communicate each other.
Oracle database server is developing based on thin protocol.
Thin protocol is proprietary to Oracle database server.
If we would like to develop a ‘C’ program to communicate with database server. The ‘C’
Program has to send the request by using thin protocol. But Oracle guys are not ready
to release thin protocol to out side market.
28
To resolve the above problem, Oracle guys are developed OCI functions (Oracle Call
Interface), these functions are developed in ‘C’ language. The code inside the OCI
functions interact with database server. Oracle guys are release OCI functions as part of
client software.
Now we can develop a ‘C’ program to communicate with Oracle database server. By
using OCI functions.
Similarly MYSQL DB Server releases MCI functions to interact with MYSQL DB Server.
29
ODBC API contains set of ‘C’ language functions.
Once the API is released, any body can provide the implementation.
The implementation is called as ODBC software or ODBC Driver.
Sun Micro System released JDBC API to develop a java program to communicate with
any database server without changing the java code.
The database server stores the data into files. These files are called as DBF files.
When the client send the request to DB server, DB Server takes the request and
encrypts the data and store the data into DBF files. If required the server program reads
the data from DBF files and decrypt the data and send to the clients.
30
Oracle database server released in the form of two versions. They are:
Enterprise edition (XE)
Express edition
As part of enterprise edition the service name port number of database server are
fixed. They are
Service Name: XE
Port No: 1521
From the above architecture we have to develop the java application which
communications with DB server.
Sun Micro System as released two packages for JDBC. They are:
Java.sql
Javax.sql
The following are the most important of class and interface java.sql package.
***java.sql interfaces:
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
DatabaseMetadata
ResultSetMetadata
***java.sql classes:
DriverManager
Types
Date
All the above companies release JDBC Driver software in the form of jar files.
We have to use this jar files to develop the java application to communicate with
database server.
We have to following the procedure to develop a java application which communicate
with DB server.
import java.sql.*;
public class DatabaseConnection{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”malli”);
System.out.println(“got the connection:” + con.getClass());
}
}
If we got the connection object successfully we can say the java program establish the
connectivity with DB server. If we fail to get the connection it throws an Exception
java.sql.Exception.
*Requirement:
Develop a java program to create a table in the database server. The table name must
be emp with eno, ename, salary as columns names.
import java.sql.*;
public class CreateTable{
public static void main(String[] args)throws SQLException{
In a project we create the tables any once before the project starts on the created
tables are performing CURD operations.
C-Create U-Update
R-Retrieve D-Delete
*Requirement: Develop a java program to create to insert a record into DBS to emp
table. We should be able to insert a record into emp table. The values are empno 1,
ename Raju and salary 1000.
import java.sql.*;
public class InsertTable{
public static void main(String args[])throws SQLException{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","malli");
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into emp values(106,'Ravi',18000)");
}
}
Execute update method returns an integer value. This integer value indicates the
number of records affected by the query in the database server. The memory of
34
effected is because of SQL query how many number of records are update, delete and
inserted the data.
Ex: int no = stmt.executeUpdate(“delete from emp where eno = 101”);
System.out.println(no);
set CLASSPATH=ojdbc14.jar;.;
Requirement:
Develop the java application to retrieve all the records from emp table and display to
the client.
When we execute the select query by using execute query method it’s a returning
ResutlSet object by using System.out.println it is display object with has code it’s not
display the data available in ResultSet object.
Ex: ResultSet rs = stmt.executeQuery(“select * from emp”);
When we send the query to JDBC driver. The send the query to data base server. DBS is
executed the query and return the records to JDBC driver. It is the responsibility of JDBC
driver to convert data into ResultSet object (rs) and this ResultSet object is return to java
application.
When even we got the result set object(rs). It is associated with a ResultSet pointer.
Initially these ResultSet pointer points to invisible record before first row.
ResultSet pointer
Get row method is used to find where the ResultSet pointer is ponting to.
35
Syn: int getRow()
When we call the next method if the next record is available it returns the true value. If
the next record is not available it returns the false.
To read the values from specific column we use get row methods. The following
diagram shows how to read the values of a specific data type.
import java.sql.*;
public class RetriveRecords{
public static void main(String[] args)throws SQLException{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","malli");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt("eno"));
System.out.println(rs.getString("ename"));
System.out.println(rs.getInt("sal"));
}
}
}
In the JDBC API when ever an Exception is occur it will throw java.sql.SQLException.
As part of the JDBC program we are trying to retrieve column which is not available a
ResultSet object. In this scenario java application throws SQLException with invalid
column name as the message.
If the ResultSet pointer is pointing to an invisible record after the last row and if we are
trying to get the values are get exausted ResultSet Exception.
When we got the ResultSet object and without calling next() method we get an
Exception ResultSet next was not call.
36
Most of the projects we try to select the records based on some criteria.
To fitter the records based on the criteria as part of the select query we must use where
clause. Retrieve all the records from emp table whose salary is > 3000.
Ex: ResultSet rs = stmt.executeQuery(“select * from emp where salary > 3000”);
*what is projection?
Display selected columns is called as projection.
Develop a java application to retrieve emp and salary from the emp table.
Ex: ResultSet rs = stmt.executeQuery(“select eno,salary from emp”);
Ex:
getxxx(columnName);
getxxx(columnIndex);
We can get the values based on column index also. The column Index starts with (1)
one.
Ex: System.out.println(rs.getString(1));
System.out.println(rs.getInt(2));
*Assignment:
Retrieve the records from the ResultSet object by using do…while loop and display to
the client.
Use a for loop to retrieve the records from ResultSet object display the client.
import java.sql.*;
public class IfDoWhile{ //using with if condition and do…while
public static void main(String[] agrs)throws SQLException{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","malli");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
if(rs.next()){
for(; rs.next() ;){
System.out.println(rs.getInt("eno"));
System.out.println(rs.getString("ename"));
System.out.println(rs.getFloat("sal"));
}
}
else{
System.out.println("There are no Records");
}
}
}
Try to create the table by using executeUpdate and check the return type of
exeucuteUpdate.
38
int no = executeUpdate(“Query”);
try to execute selectQuery by using executeUpdate and check the return value.
ResultSet rs = executeQuery(“Query”);
*PreparedStatement:
PreparedStatement is also used to send the queries to DBS.
PreparedStatement improves the performance of java application when compared
with statement object.
By using PreparedStatement also we can perform CURD operations.
C-create a record
U-update a record
R-retrieve records
D-delete a record
*Requirement:
Develop a java application to insert a record into emp table by using prepared
statement?
import java.sql.*;
public class PreparedInsertRecord{
public static void main(String[] args)throws SQLException{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","malli");
PreparedStatement pstmt = con.prepareStatement("insert into emp values(?,?,?)");
pstmt.setInt(1,102);
pstmt.setString(2,”Raju”);
pstmt.setDouble(3,5000);
int no = pstmt.executeUpdate();
39
System.out.println(no);
con.close();
}
}
import java.sql.*;
public class PreparedStatementUpdate{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con=
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesavcherry");
PreparedStatement pstmt = con.prepareStatement("update student555 set sno = ?
where marks = ?");
pstmt.setInt(1,102);
pstmt.setFloat(2,99);
int no = pstmt.executeUpdate();
System.out.println(no);
con.close();
}
}
By using PreparedStatement object we can execute any type of Queries that is Insert,
Update, Delete and Retrieve records.
It is the responsibility of DataBase Server to improve the performance of the same
query is sent for the second time.
When we sent the query second time with a small changes in it , database server treats
the query as different query and process all the steps.
Even if then is change we are use of the query database treat as different query.
The following steps will be carried out by the DB server when the query is send to it.
The database server checks the query. If it is invalid it thrown an exception.
Database server checks where there all the records are available or not if not
available it will display the error message.
Database convert the query into its understandable language.
As part of database server prepares couple of algorithms to get the data from
database files.
Database stores algorithm with queries in the SGA (System Global Area) memory
of database server.
Based on the batabase check get the best database server algorithm.
40
7. It execute the algorithm and get the data from database files and sent to client.
When to choose statement and prepared statement. When even a sending queries UN
difficult it not modify then recommended using statement.
If the same query with the different values are going to DBS. Then recommended to use
prepared statement.
DBS has given the solutions if you sending same query with different values to database
server. These problems we use bind variables.
41
Ex: Select * from emp where eno =:veno
When even the JDBC driver is ‘n’ commands prepared statement. The JDBC
driver commands prepared statement into bind variables.
When even we call the setter methods JDBC driver supply the values to bind
variables.
Prepared statement will not improve the performance when the query goes to
database server for the first fine. This is because first time database server has
to execute all the steps.
In a project we should never use Scott and tiger we always use our user name to
login database server by using system user.
10. We have to use the following command to create a new user in database server.
Create user kesav identified by kesav cherry;
Grant connect, resource to kesav;
We must follow the following to best practices when we write the JDBC code.
Always recommended to practice the query in SQL*plus and use it a java
application.
It is always recommended to display what is the query which sends to java
application. We can achieve this by the writing the query in a variable and display
the query.
*Develop a JDBC program to get data from keyboard (Buffered Reader) store the data
into employee table. Use prepared statement?
import java.io.*;
import java.sql.*;
public class PreparedBufferedReader{
public static void main(String arga[])throws
IOException,SQLException{ BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); System.out.println("Enter employee
number:"); String eno = br.readLine();
System.out.println("Enter employee name:");
String name = br.readLine();
System.out.println("Enter employee salary:");
String salary = br.readLine();
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
42
Connection con= DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesavcherry");
String query = "insert into emp
values(?,?,?)"; System.out.println(query);
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1,eno);
pstmt.setString(2,name);
pstmt.setString(3,salary);
pstmt.executeUpdate();
}
}
import java.util.*;
import java.sql.*;
public class Statementsanner{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("eno");
int eno = s.nextInt();
System.out.println("name");
String name = s.next();
System.out.println("salary");
double salary = s.nextDouble();
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con= DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesavcherry");
Statement stmt = con.createStatement();
String query = "insert into emp values("+eno+",' "+name+" ',"+salary+")";
System.out.println(query);
stmt.executeUpdate(query);
}
}
By using JDBC we cannot execute the queries which are specific to a particular DBS.
Callable statement:
Callable statements are used to call the procedures from java application.
Calculate the bill amount to all the customers which are available in customer table.
43
import java.sql.*;
public class BSNLbill{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesavcherry");
String query = "Select * from BSNLcustomer";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
int noofc = rs.getInt("noofc");
double bamount = noofc * .10;
int phoneno = rs.getInt("phoneno");
String UQuery = "update BSNLcustomer set bamount = ? where phoneno
= ?"; //System.out.println(UQuery);
PreparedStatement pstmt = con.prepareStatement(UQuery);
pstmt.setDouble(1,bamount);
pstmt.setInt(2,phoneno);
pstmt.executeUpdate();
}
}
}
The disadvantage above approach we are in tract with database server from multiple
times through networks. Because of this we get the performance issue we can resolve
this by using processors.
We can write the processor with business logic. Processor in database server processor
run’s inside database server.
When even any body call processor database server run’s it processor improves
performance of project.
44
We can use three types of procedures.
A procedure which doesn’t take any type of parameters.
A procedure which takes input parameter.
A procedure input parameter as well as output parameter.
*How to create procedure in database?
create or replace procedure MyProc
as
begin
insert into emp values(2,’naveen’,2000);
end MyProc;
/
*To execute the Procedure from the client we use a command exec MyProc;
The following procedure which takes input parameter.
1 create or replace procedure MyProc(veno IN number,
2 vname IN varchar2, vsalary in number)
as
begin
insert into emp values(veno, vname, vsalary);
end MyProc;
/
*To run the above procedure we use the following command exec MyProc(1,’abc’,2345);
begin
45
result := no1 + no2;
end addition;
/
exec addition;
exec addition(10,20, :result);
print result;
*To call the above procedure we have to perform the following steps.
Step 1: Before we call the procedure we must register / create variable. (/ slash)
Step 2: Call the procedure by supplying bind variable as input.
Step 3: After procedure is executed we can get the value from out variable and display.
*Develop a java application to call a procedure which doesn’t take any parameter.
}
}
*Develop a java application to call the procedure which takes Input parameters.
SQL>
create or replace procedure MyProc(Veno in number,
Vname in varchar2, Vsalary in number) as
begin
insert into emp values(Veno, Vname, Vsalary);
end MyProc;
/
import java.util.*;
import java.sql.*;
public class CallProcedure{
public static void main(String[] args)throws SQLException{ Scanner s
= new Scanner(System.in); DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
46
Connection con = DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:xe”,”kesav”,”kesav cherry”);
CallableStatement cstmt = con.prepareCall(“{call MyProc(?,?,?)}”);
cstmt.setInt(1,s.nextInt());
cstmt.setString(2,s.next());
cstmt.setInt(3,s.nextInt());
cstmt.execute();
}
}
*Develop a java application to call a procedure which takes input parameter and output
parameter?
create or replace procedure addition(Vno1 in number,
Vno2 in number, Vresult out number) as
begin
result := Vno1 + Vno2;
end addition;
/
import java.sql.*;
public class CallableStatement{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle:jdbc:driver:OracleDriver()); Connection con =
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:xe”,”kesav”,”kesav cherry”);
CallableStatement cstmt = con.prepareCall(“{call addition(?,?,?)}”);
cstmt.setInt(1,11);
cstmt.setInt(2,22);
cstmt.registerOutParameter(3,Types.INTEGER);
cstmt.execute();
int result = cstmt.getInt(3);
System.out.println(result);
}
}
47
When we register out parameter it is responsibility of JDBC driver to declare a
variable. One in the procedure is executed the value will store in the variable.In oracle
we can use functions. They are two types of function are available in oracle.
Predefined functions (or) aggregate functions
User defined functions
*Develop a java application to find the number of records available in emp table?
import java.sql.*;
public class FindRecords{
public static void main(String[] main)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OralceDriver()); Connection con =
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost”,”kesav”,”kesav cherry”);
Statement stmt = con.createStatement();
ResutlSet rs = stmt.executeQuery(“select count(*) count from emp”);
if(rs.next()){
System.out.println(rs.getInt(“count”));
}
}
cstmt.setInt(3,33);
cstmt.execute();
int sum = cstmt.getInt(1);
System.out.println(sum);
}
}
*Types of ResultSets: They are two types of ResultSets in java. They are
Forwardonly ResultSet
Bi-Directional ResultSet
49
create statement(ResultSet TYPE,ResultSet CON CURRENCY);
for ResultSet TYPE we can supply any of the following three values.
TYPE_FORWARD_ONLY By Default
TYPE_SCROLL_SENSITIVE
TYPE_SCROLL_INSENSITIVE
For ResultSet Con Currency we can supply any of the following two values.
CONCUR_READ_ONLY By Default
CONCUR_UPDATABLE
After modify the data in database server if it is not reflecting in ResultSet object we all it
as Insensitive.
When we use CONCUR_UPDATABLE when even we modify the data in ResultSet object
it get reflected in database server.
Ex:
import java.sql.*;
public class ResultSetTypeStatement{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs.next();
System.out.println(rs.getRow());
rs.previous();
System.out.println(rs.getRow());
rs.previous();
System.out.println(rs.getRow());
con.close();
}
50
}
When we call the previous() method the ResultSet pointer is placed to old recored.
Absoulte(): This method is used to move the ResultSet pointer to a specific Record/Row.
Ex: rs.absolute(5);
th
When the above line is executed to ResultSet pointer is placed at 5 Row. We
can use Bi-Directional ResultSet in case of prepared statement object also. Ex:
PreparedStatement pstmt = con.prepareStatement(“select * from emp”
,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
Ex: To develop a sensitive ResultSet program we must follow the follow three steps.
Make the ResultSet object as sensitive
Use the refreshRow() method
In the Query instead of * we must use column names.
import java.sql.*;
public class ResultSetTypeReadOnly{
public static void main(String[] args)throws
Exception{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statementstmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
When ever java program has en counter a refreshRow() it will check the data in
database server and the data in ResultSet object same or not. If they are not same
refreshRow() will update the data in ResultSet object.
51
refreshRow() method work only from sensitive ResultSet.
In the SQL query instead of * we are specified column names. This in because when
ever then the change in specific column the JDBC Driver update the specific column
only.
Develop a java application to retrieve the records un updated a specific records in the
ResultSet object by using CONCURRENT updatable?
Ex:
import java.sql.*;
public class Absolute{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select eno, ename, sal from emp");
rs.absolute(3);
rs.updateDouble("sal",22000);
rs.updateRow();
}
}
import java.sql.*;
public class MoveToInsertRow{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select eno,ename,sal from emp");
rs.moveToInsertRow();
rs.updateInt(1,123);
rs.updateString(2,"veera");
rs.updateDouble(3,19000);
rs.insertRow();
}
}
52
th
*Develop a java application to retrieve the records from emp table and delete the 4
record?
To achieve the above requirement we can a method delete Row.
import java.sql.*;
public class AbsoulteDeleteRow{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select eno,ename,sal from emp");
rs.absolute(9);
rs.deleteRow();
}
}
When ever we create the statement object immediately a Batch object will be
created. This Batch object is associated with statement object.
Ex: Statement stmt1 = con.createStatement();
Statement stmt2 = con.createStatement();
53
Requirement:
*Develop a java application to insert three records by using Batch updates?
import java.sql.*;
public class InsertBatchRecords{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statement stmt = con.createStatement();
stmt.addBatch("insert into emp
values(122,'niranjan',16666)"); stmt.addBatch("insert into
emp values(124,'sravan',11143)"); stmt.addBatch("insert into
emp values(125,'mrudhu',14371)"); stmt.executeBatch();
}
}
By using object we can add insert, update and delete queries. By using Batch updates
we can not perform select operations.
Syntax of execute: int a[] executeBatch();
The size of integer array is dependent on the size of the Batch object. The integer array
contains the values which are got effected by each and every query. We can print these
values by using a loop.
Ex: for(int i = 0;i<a.length;i++){
System.out.println(a[i]);
}
While working with Batch updates if any query in the batch object is failed. JDBC driver
throws java. Sql.BatchUpadeException.
Once if we sent the Batch object to database server we can clear the Batch by using
cleared Batch method.
54
*Requirement: insert three records into emp table by using prepared statement?
import java.sql.*;
public class PreparedBatchInsert{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
PreparedStatement pstmt = con.prepareStatement("insert into emp values(?,?,?)");
pstmt.setInt(1,133);
pstmt.setString(2,"suneel");
pstmt.setDouble(3,15500);
pstmt.addBatch();
pstmt.setInt(1,144);
pstmt.setString(2,"sudheer");
pstmt.setDouble(3,9876);
pstmt.addBatch();
pstmt.executeBatch();
}
}
import java.sql.*;
public class PreparedBsnlBill{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav","kesav cherry");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from BSNLCUSTOMER");
PreparedStatement pstmt = con.prepareStatement
("update bsnlcustomer set bamount = ? where phoneno = ?");
while(rs.next()){
int noofc = rs.getInt("noofc");
int phoneno = rs.getInt("phoneno");
double bamount = noofc * 0.10;
pstmt.setDouble(1,bamount);
pstmt.setInt(2,phoneno);
pstmt.addBatch();
55
}
pstmt.executeBatch();
}
}
When the new versions of specifications are released then all new interfaces and new
methods in the existing interfaces.
56
As part of JDBC4.0 specification sun micro system has added a feature to register the
driver automatically (DriverManager.getConnection).
We can find the specification implementation version as part of META_INF folders.
When we work with JDBC4.0 to register JDBC driver automatically we need to make
sure that we set the CLASSPATH to ojdbc6.jar.
Theoretically speaks a driver can communicate with any DB server when we consider
oracle JDBC Driver. They have provided the code to communicate only with oracle DB
server.
We cannot use oracle JDBC Driver to communicate with Mysql Database Server.
*Develop a java application to insert a record into emp table of mysql database server?
import java.sql.*;
public class MysqlInsertRecords{
public static void main(String[] args)throws Exception {
Class.forName("com.mysql.jdbc.Driver"); Connection
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb"."root","kesav");
Statement stmt = con.createStatement();
int no = stmt.executeUpdate("insert into emp values(999,'Mohan',60000);
System.out.println(no);
57
}
}
***The problem with above code is we have hard coded. Driver class, URL, USER_NAME
and password because of these reason we are able to insert with only one DB server. If
we want to same java program to insert with any database server without changing the
code we should able to remove the hard coding.
*The following an example of java application which can be used to interact with any
database server?
import java.sql.*;
public class AnyDatabaseServerInsertRecord{
public static void main(String[] args)throws SQLException,ClassNotFoundException{
String drv = System.getProperty(“drv”);
String url = System.getProperty(“url”);
String uname = System.getProperty(“uname”);
String pwd = System.getProperty(“pwd”);
Class.forName(drv);
Connection con = DriverManager.getConnection(url,uname,pwd);
Statement stmt = con.createStatement();
int no = stmt.executeUpadate(“insert into emp values(888,’RajuRani’,143);
System.out.println(no);
}
}
Transactions: (performing)
Performing sequence of steps in single unit is called as Transacion.
Every transaction will have a staring point and ending point.
Every transaction is having two states.
3.1. Success state
3.2. Failure state
If all the steps in the transaction are executed successfully then we say
transaction is success. If any one step is failed we can say transaction is failed.
Once if one transaction is ended a new transaction will be started. In a project we
can have any number of transactions. It is based on the project requirement.
When ever carryout performing any operations with database server he is
responsible to start the transaction.
When even we establish connection with database server he starts a transaction.
After establish the connection with database server. When the user perform any
operation. The data will store permanently when we end the transaction.
When one transaction is completed it is the responsibility of database server to
start another transaction.
10. By default it is the responsibility of JDBC driver to start a transaction as well as to
end the transaction.
11. When the JDBC driver starts the transaction. When ever we establish connection
with database server immediately JDBC driver starts the transaction.
12. When the JDBC driver ends the transaction. When ever we send a query to
database server immediately JDBC driver ends the transaction.
13. When we establish the connection internally JDBC driver uses
“con.setAutoCommit(true); or con.setAutoCommit(false); and con.rollBack();”.
The above application is used to capture employee details and store it in a DBS. Our
application should be able to support dealing with multiple address. To achieve the
above requirement we have two designs.
Design1: In this design we create only table.
The disadvantage of this approach is we find the duplicate data in the table. It is not
recommend using design1.
Design2: In this design we will try to have two tables. They are emp and Address tables.
*The following example of user defined transactions to store the data into multiple
tables?
import java.sql.*;
import java.util.*;
public class InsertTwoTableRecords{
public static void main(String[] args)throws SQLException{
Scanner s = new Scanner(System.in);
60
System.out.println("Enter the employee number");
int eno = s.nextInt();
System.out.println("Enter the employee ename");
String ename = s.next();
System.out.println("Enter the employee salary");
double salary = s.nextDouble();
System.out.println("Enter the employee street");
String street = s.next();
System.out.println("Enter the employee city");
String city = s.next();
System.out.println("Enter the employee state");
String state = s.next();
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav”,”kesav cherry”);
con.setAutoCommit(false);
PreparedStatement pstmt1 = con.prepareStatement("insert into emp2 values(?,?,?)");
pstmt1.setInt(1,eno);
pstmt1.setString(2,ename);
pstmt1.setDouble(3,salary);
PreparedStatement pstmt2 = con.prepareStatement
("insert into address values(?,?,?,?)");
pstmt2.setInt(1,eno);
pstmt2.setString(2,street);
pstmt2.setString(3,city);
pstmt2.setString(4,state);
pstmt1.executeUpdate();
pstmt2.executeUpdate();
con.commit();
}
}
It’s not recommended to use throws as for the project. It’s always recommended to use
try and catch blocks. By using try and catch block we can handle the errors.
When JVM executes a piece of code and if it fails JVM check for appropriate error
handler. If it is available JVM execute the code if the error handler not available the JVM
throws an error to the client (Exception stack trees).
61
As per as catch block we will provide the code when an exception is raised what code is
executed.
There are some scenarios when we want execute the code. When the exception doesn’t
occur we provide this code in finally block.
import java.sql.*;
import java.util.*;
public class DBConnectionTwoTables{
public static void main(String[] args)throws Exception{
Scanner s = new Scanner(System.in);
System.out.println("Enter the employee number");
int eno = s.nextInt();
System.out.println("Enter the employee ename");
String ename = s.next();
System.out.println("Enter the employee salary");
double salary = s.nextDouble();
System.out.println("Enter the employee street");
String street = s.next();
System.out.println("Enter the employee city");
String city = s.next();
System.out.println("Enter the employee state");
String state = s.next();
Connection con = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
ResultSet rs = null;
con.setAutoCommit(false);
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","malli");
con.setAutoCommit(false);
pstmt1 = con.prepareStatement("insert into emp2 values(?,?,?)");
pstmt1.setInt(1,eno);
pstmt1.setString(2,ename);
pstmt1.setDouble(3,salary);
pstmt2 = con.prepareStatement("insert into address values(?,?,?,?)");
62
pstmt2.setInt(1,eno);
pstmt2.setString(2,street);
pstmt2.setString(3,city);
pstmt2.setString(4,state);
pstmt1.executeUpdate();
pstmt2.executeUpdate();
}catch(SQLException se){
con.rollback();
System.out.println("some code is missing");
}finally{
con.close();
pstmt1.close();
pstmt2.close();
rs.close();
}
}
}
When even we provide user defined transactions. We must connect the transaction in
try block. We must provide rollback in side catch block.
import java.sql.*;
public class DBServerConnectType4C{
public static void main(String[] args)throws SQLException{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","malli");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from emp");
System.out.println(con);
System.out.println(stmt);
System.out.println(rs);
}catch(SQLException s){
}finally{
63
con.close();
rs.close();
stmt.close();
}
}
}
*connection is an interface:
How come we are able to create object to connection interface?
We are not creating object to connection interface, we are creating a reference variable
to connection interface. These reference variables hold an object of a class which
provides an implementation of connection interface.
The internal code of implementation class is responsible to really established
connection with DB server.
*MetaData:
Data about data is called as MetaData.
In JDBC we have three types of MetaData available. They are:
ResultSetMetaData
DatabaseMetaData
ParameterMetaData
*ResultSetMetaData:
ResultSetMetaData is an object which gives more information about ResultSet object.
By using ResultSetMetaData object we can find the number of column is available in
ResultSet, the names of the columns, the Data types of the columns. Ex:
ResultSetMetaData rsmd = rs.getMetaData();
import java.sql.*;
public class RSMDConnection{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav”,”kesav cherry”);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println(rsmd.getColumnCount());
System.out.println(rsmd.getColumnName(2));
System.out.println(rsmd.getColumnTypeName(2));
System.out.println(rsmd.isSearchable(2));
System.out.println(rsmd.getColumnType(2));
}
}
Sun micro system as given a class java.sql.types this class doesn’t contain any methods.
This class contains only static and final variables. We will never instantiate the type’s
class this is because it doesn’t contain any methods. This class is used to map generic
SQL types.
*DatabaseMetaData:
By using DatabaseMetaData we can find the information about underline Database
Server. The information like version number of Database server, JDBC Driver version as
well as JDBC specifications also.
import java.sql.*;
public class DatabaseMetaDataConnection{
public static void main(String[] args)throws
SQLException{ DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver()); Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","kesav”,”kesav cherry”);
DatabaseMetaData dbmd = con.getMetaData();
66
System.out.println(dbmd.getDatabaseMajorVersion());
System.out.println(dbmd.getDatabaseMinorVersion());
System.out.println(dbmd.getDatabaseProductName());
System.out.println(dbmd.getDriverMajorVersion());
System.out.println(dbmd.getDriverMinorVersion());
System.out.println(dbmd.getJDBCMajorVersion());
System.out.println(dbmd.getJDBCMinorVersion());
}
}
Generally we use DatabaseMetaData at the time of installing the software. It will check
the underline Database server version is match with required DBS’s or not.
*ParameterMetaData:
This object is used to find the information about perameters of PreparedStatement.
To work with PerameterMetaData first we must get PreparedStatement object. We use
a method getParameterMetaData.
All Driver vendors as not provide the implementation to all the methods of
ParameterMetaData.
*Types of Drivers:
They are 4 types of JDBC Drivers are available in the market.
TYPE 1: JDBC-ODBC Bridge Driver
TYPE 2: Native API Driver
TYPE 3: Network protocol Driver
TYPE 4: Pure java Driver/thin Driver
67
*Disadvantages of type 1 driver:
If we would like work with type one JDBC driver. Developer/Client as to install
software of database to get CI functions we have install ODBC Driver software and
JDBC driver software and JDBC driver software. We have to configure JDBC driver
to communicate with ODBC Driver.
Type1 Driver is platform dependent this is because CI functions are developed in
‘C’ language.
MS as released ODBC API to develop a ‘C’ program to interact with any database
server. The internal code of the ODBC drivers uses OCI functions(native functions)
to communicate with Database servers.
If the .DLL’s are not available in ODBC driver software we have install then
separately.
Type1 JDBC Driver is developed by only sun micro system. No body else has
developed type1 JDBC Driver. Sun micro system has integrated type1 JDBC Driver
with java software only. We no need to install type1 JDBC Driver saperatly.
When we observe the .DLL file of oracle we have found that internally it is use it
ODBC API functions. The function survive SQL connect, SQL disconnect, SQL
execute and etc. these functions internally communicate with OCI functions.
68
From the driver configure window provide data source name, description, userid and
click on “OK”.
When we use type1 driver the JDBC Driver calls has to be translated to ODBC calls has
be translate to JDBC calls. Because of these reason we see a performance impact. This
driver is slowest in all the Drivers.
This is not at all recommended to use develop web applications.
*Requirement:
Develop a java program application to read the data from MS access file system by using
type1 driver?
MS Access is not a DB server , it is a File.
DriverManager.registerDriver(new sun.jdbc.odbc.jdbcOdbcDriver());
Connection con = DriverManager.getConnection(“jdbc:odbc:mysqlds”,”kesav”,”kesav”);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“select * from emp”);
import java.sql.*;
public class RetriveRecords3{
public static void main(String[] args){
DriverManager.registerDriver(new sun.jdbc.odbc.jdbcOdbcDriver());
Connection excelcon = DriverManager.getConnection("jdbc:odbc:myds","","");
Statement excelstmt = excelcon.createStatement();
ResultSet rs = excelstmt.executeQuery("select * from [emp$]");
Connection oraclecon = DriverManager.getConnection
("jdbc:odbc:oracleds","kesav","kesav cherry");
PreparedStatement pstmt = oraclecon.prepareStatement
("insert into emp values(?,?,?,)");
while(rs.next()){
pstmt.setString(1,rs.getString(1));
pstmt.setString(2,rs.getString(2));
pstmt.setString(3,rs.getString(3));
pstmt.addBatch();
}
pstmt.executeBatch();
}
}
70
*Advantages of type4 driver:
This Driver is development in pure java. Because of those we can say this Driver is
platform independent.
This is fastest Driver in all the Drivers. This is because Driver directly
communicates with database server.
We need to install any client software.