File - my World....!

advertisement

JDBC(Java DataBase Connectivity)

 Driver is a Java Program.

 Driver is a software, which is provided by database vendors

Java prog ram

Interface driver database

Sun has specified 4 types of Drivers in JDBC specification

1.

Type I Driver : JDBC-ODBC Bridge

2.

Type II Driver : Partially native and partically Java Driver

3.

Type III Driver : Net-protocol Driver

4.

Type IV Driver : Pure Java Driver

Type I Driver : JDBC-ODBC Bridge Driver :

 ODBC Driver is developed by Microsoft. This is available in windows operationg System only.

 ODBC Driver is developed in C Language.

 Type I Driver supports all the databases. java program

JDBC

Driver

ODBC

Driver database

Java call jdbc call

To

ODBC call to

ODBC call native call(SQL call)

Name : Jdbc-Odbc Bridge Driver

Driver class name : Sun .jdbc.odbc.JdbcOdbc Driver

URL : jdbc : odbc : DSN Name

UserName : Database dependents

Password : database dependents

Vendor : Sun Micro System

Software Requirements : j2sdk1.4

Path : Not required

Class path : Set classpath = %classpath%;d:\j2sdk1.4\lib;

Advantages : i.

It supports all the databases ii.

Performance is acceptable iii.

It is suitable for migration projects, which still wants to use odbc driver

Disadvantages : i.

It is limited to only windows operating system ii.

It is not suitable for performance oriented applications.

Note : i.

Odbc driver is implemented in C language by MicroSoft. ii.

Performance is not very high, because internally it has to make lot of conversions, i.e, jdbc requests to odbc request, and then odbc request to native request.

Steps to write a Jdbc Program : i.

Load the driver class into the memory. ii.

Establish the connection to the database server. iii.

Create the statement. iv.

Prepare the SQL statement and execute it. v.

Process the results. vi.

Close the statement and connection.

JDBC API :-

Java.sql is a package given by the Sun to write the JDBC programs.

Class

1.

Driver manager

Interface

1. Connection

2.

Types 2. Statements

3.Prepare statement

4. Callable Statements

5. Result Set

6. Databases Metadata

7. Result set MetaData.

JDBC Steps : - i.

Load the driver class name

Calss.for name(“sun.jdbc.odbc.JdbcOdbcDriver”); ii.

Establish the connection

Connection con=DriverManager.getConnection(“jdbc.odbc.SriDSN”,

”scott”,”tiger”);

*. Getconnection is a static method in Driver Manager class. iii.

Create the statement

Statement s=con.createStatement(); iv.

Prepare the query and execute it.

String.sql=”select * from studen”;

Result rs=s.executeQuery(sql); v.

Process the results

While(rs.next())

{

S.o.p(rs.getInt(1));

S.o.p(rs.getString(2));

S.o.p(rs.getString(3));

} vi.

Close the statement and connection. sid Name email rs.close(); s.close(); con.close();

 Sub classes of all the interfaces are written by database vendors who created the driver.

Statement s=con.createStatement();

Interface

 Here statement is an interface and so, an interface can not have a object ‘s’. To do so they have created subclass of the interface in the driver. So this is the reason why here the interface have an object.

All these subclasses are loaded into the memory. In a driver all the static classes are present. So it loads it self.

Steps to create DSN(DataSourceName) :- i.

Open the controlpanel

Start -> settings -> control panel ii.

Open administrative tools iii.

Data sources odbc (press enter). iv.

Click on add button. v.

Select the driver

For oracle ; oracle ODBC Driver and click FINISH vi.

Provide DataSourcename, service_name, user_name and click on oK vii.

Click on OK

If you installed oracle in D:

D:\oracle\ora91\network\ADMIN\tnsnames.ora

1.

Host : local host

2.

Port number : 1521

3.

Service name or sid or gid : javaSeshu

4.

D:\oracle\ora91\jdbc\lib\classes111.jar

Steps to create DSN

5.

Select the drive called oracle in orahome91 and click on Finish

6.

Provide datasource name,service name, username and click on test connection.

7.

Enter password and click ok.

Example usint Type I driver. .

1.

Create the DSN called sd

2.

Create the table called student and insert some records and issue commiot. create table student( sid number(5),

Sname char(20),

Email char(20)); insert into student values(99,’jagadeesh’,’siddu.hasini’); insert into student values(88,’jai’,’jag.alex’);

3.

Write the jdbc program import java.sql.*; class jdbcEx

{ public static void main(string a[ ])

{

int sid=0;

String sname=null,email=null;

Try

{

//1. Load the driver

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

//2. Get the connection

Connection con=DriverManager.getConnection(

“jdbc : odbc : sd”,”scott”,”tiger”);

//3. Crete the statement

Statement st=con.createStatement();

//4. Prepare the query and execute it

String sql=”select * from student”;

ResultSet rs=st.executeQuery(sql);

//5. Process the results while (rs.next())

{

sid=rs.getInt(1);

sname=rs.getString(2);

email=rs.getStirng(3);

System.out.println(“ “+sid+”\t”+sname+”\t”+email);

}

//6.close rs.close(); st.close(); con.close();

}

Catch(Exception e)

{

e.printStackTrace();

}

}

}

Type II Driver : -

Name : partially native_partly java Driver

Vendor : DB vendor

S/W required : DB client / Server Edition.

Path : set path = %path%; d:\oralce\ora91\bin;

Class path : set classpath= %classpath%; d:\oracle\ora91\jdbc\lib\classes111.jar

Note : Install the client s/w in the client machine and server s/w in server machine and set the path and classpath in both the machines. (Network Driver)

Driver class Name : oracle.jdbc.driver.OracleDriver url : jdbc : oracle : oci8: @hostname : port number ipaddress : sid ex : jdbc: oracle : oci8 : @localhost : 1521 : javaSeshu username : scott password : tiger

Architecture : -

Client machine Server

Jdbc program

SQL

Engine

DB library

DB

Library

Pros (or) Advantages : i.

It is compatible with all the operating systems ii.

It is good in the performance when compared with Type I

iii.

It is suitable for intranet applications. iv.

It supports all the databases which supports client/server Editions

Cons (or) Disadvantages : - i.

It is not suitable for internet applications. ii.

You need to install the data library in client machine.

Type III Driver : -

If you want to use this driver, you must install

Ids server platform independent & Database Indepenes

Name : Net Protocol Driver

Vendor : Ids software (you must use their server only)

S/W required : Ids Server

Path :

Class path :

Driver class name : com.ids.Driver url : jdbc:ids://localhost/dbname username : dbrelated password : dbrelated

Architecture :

Client machine middlewareserver

Jdbc program IDS

bdserver

SQL

Engine

Type IV Driver : -

DB

LIBRARY

Name : Pure java Driver

Vendor : DB vendor

S/W required : DB

Path : d:\oracle\ora91\bin;

Class path : d:\oracle\ora91\jdbc\lib\class111.jar

Note : Set the path and classpath on server machine driver class name : oracle.jdbc.driver.OracleDriver url : jdbc : oracle :thin:@localhost :1521 : javaSeshu username : scott password : tiger

For MySQL : -

Class path : set classpath=%classpath%;e:\b8\jdbc\MySql.jar;

DB

LIBRARY

MySql_connector_java_3.1.1.2_bin.jar

Change this one as MySQL.jar

Username : root

Password : javaSeshu

Driver class name : com.mysql.jdbc.Driver url : jdbc:MySql://LocalHost/dbname

Architecture : -

Client Machine

Jdbc program

Jdbc API interface Connection

{

TRANSACTION_NONE;

TRANSACTION_READ_UNCOMMITED;

TRANSACTION_READ_COMMITED;

TRANSACTION_REPEATABLE_READ;

TRANSACTION_SERIALIZABLE;

Statement create Statement();

PrepatedStatement prepareCall(String);

CallableStatement prepareCall(String);

DB server

SQL engine

DB Library

void setAutoCommit(Boolean); boolean getAutoCommit(); void commit(); void rollback(); void close(); boolean isClosed();

DatabaseMetaData getMetaData(); void setReadOnly(Boolean); boolean isReadOnly(); void setTransactionIsolation(int); int getTransactionIsolation();

Statement createStatement(int,int);

PreparedStatement preparedStatement(String,int,int);

CallableStatement prepareCall(String,int,int);

Map getTypeMap(); void setTypeMap(Map);

Statement createStatement(int,int,int);

PreparedStatement preparedStatement(String,int,int,int);

CallableStatement prepareCall(String,int,int,int);

PreparedStatement preparedStatement(String,int);

}

Driver Manager class

Interface Driver

{

int getMajorVersion(); int getMinorVersion();

}

Statement Interface : interface Statement

{ iInt getResultSetType(); void close(); void setFetchDirection(int); int getFetchDirection(); void addBatch(String); void clearBatch() int[ ] executeBatch(); int executeUpdate(String); boolean execute(String);

ResultSet executeQuery(String);

}

PreparedStatement Interface : iinterface PreparedStatement extends Statement

{ void setxxx(int,xxx); boolean execute(); int executeUpdate();

ResultSet executeQuery();

ResultSetMetaData getMetaData();

}

CallableStatement Interface : interface CallableStatement extends PreparedStatement

{ xxx getxxx(int); void setxxx(String,xxx); void registerOutParameter(int,int); void registerOutParameter(int,int,int); void registerOutParameter(int,int,String); void registerOutParameter(String,int); void registerOutParameter(String,int,int); void registerOutParameter(String,int,String);

}

ResultSet Interfaces :

Interface ResultSet

{

FETCH_FORWARD;

FETCH_REVERSE;

FETCH_UNKNOWN;

TYPE_FORWARD_ONLY;

TYPE_SCROLL_INSENSITIVE;

TYPE_SCROLL_SENSITIVE;

CONCUR_READ_ONLY;

CONCUR_UPDATABLE; int getFetchDirection(); int getType(); void afterLast(); void beforeFirst(); void cancelRowUpdates(); void close(); void deleteRow(); void insertRow (); void moveToCurrentRow(); void moveToInsertRow(); void updateRow(0; boolean first(); boolean isAfterLast(); boolean isBeforeFirst(); boolean isFirst(); boolean isLast(); void last(); boolean next(); boolean previous(); boolean rowDeleted(); boolean rowInserted(); boolean rowUpdated(); xxx getxxx(int);

boolean absolute9int); boolean relative(int); void updatexxx(int,xxx);

}

ResultSetMetaData Interface interface ResultSetMeataData

{ int getColumnCount(); int getColumnDisplaySize(int); int getColumnType(int); boolean isAutoIncrement(int); boolean isCurrency(int); boolean isReadOnly(int); boolean isWritable(int);

String getColumnClassName(int);

String getColumnLabel(int);

String getColumnName(int);

String getColumnTypeName(int);

String getTableName(int);

}

Database MetaData Interface interface DatabaseMetaData

{ int getDatabaseMajorVersion();

int getDatabaseMinorVersion(); int getDefaultTransactionIsolation(); int getDriverMajorVersion(); int getDriverMinorVersion(); int getJDBCMajorVersion(0; int getJDBCMinorVersion(); int getMaxConnections(); boolean supportsAlterTableWithDropColumn(); boolean supportsBatchUpdates(); boolean supportsExpressionsInOrderBy(); boolean supportsFullOuterJoins(); boolean supportsGroupBy(); boolean supportsMultipleResultSets(); boolean supportsMultipleTransactions(); boolean supportsOuterJoins(); boolean supportsSavepoints(); boolean supportsStatementPooling(); boolean supportsStoredProcudures(); boolean supportsTransactions(); boolean supportsUnion(); boolean supportsUnionAll(); boolean supportsResultSetType(); boolean supportsTransactionIsolationLevel(int);

String getDatabaseProductName();

String getDatabaseProductVersion();

String getDriverName();

String getDriverVersion();

String getUserName();

}

Example using Type-IV driver in MySql :

1.

Create table student in mysql create table student

(sid int, sname char(10), dob date, feebal double);

2.

JdbcEx2.java

Class JdbcEx2

{

P s v m(String a[ ])

{

try

{

Class.forName(“com.mysql.jdbc.Driver”);

Connection con=DriverManager.getConnection

(“jdbc:mysql://127.0.0.1/b8db”,”root”,”javaSeshu”);

Statement st=con.createStatement();

String str=”insert into student values(

/*Before Running do this

Set classpath=%classpath%;e:\b8\jdbc\mysql.jar;*/

Import java.sql.*;

class JdbcEx1

{ p s v m(String args[])

{

Connection con=null;

Statement st=null;

ResultSet rs=null; int sid=Integer.parseInt(args[0]);

String sname=args[1];

String email=args[2];

String dob=args[3]; double feebal=Double.parseDouble(args[4]);

try

{

Class forName(“com.mysql.jdbc.Driver”);

Connection con=DriverManager.getConnection(“jdbc:mysql://127.0.0.1/b8db”,”root”,”javaSeshu”);

St=con.createStatement();

String str=”insert into student values(“ +sid+”,’”+sname+”’,’”+email+”’,’”+dob+”’,”+feebal+”); int x=st.executeUpdate(str); if(x==1) s o p(“inserted successfully”); else s o p(“not inserted successfully”);

String sql=”select * from student; rs=st.executeQuery(sql); while(rs.next())

{ sid=rs.getInt(1) sname=rs.getString(2); email=rs.getDate(4).toString(); feebal=rs.getDouble(5); s.o.p(“*”+sid+” “+sname+” “+email+” “+dob+” “+feebal);

}

}catch(Exception e)

{ e.printStackTrace();

}

Finally

{

Try

{

If(rs!=null) rs.close(); if(st!=null) st.close(); if(con!=null) con.close();

}

}

}

}

Catch(Exception e)

{

e.printStackTrace();

}

Types of Statements

We have 3 types of statements in Jdbc

1.

Simple Statements

2.

Prepared Statements

3.

Callable Statements

For these 3 types of statements Sun has provided three interfaces in java.sql package i. Statement

Ii. Prepared Statement

Iii. Callable Statement

 Statement interface has 3 methods to execute the query i.

ii.

boolean execute(String); int execute iii.

resultSet executeQuery(String);

 PreparedStatement interface has 3 methods to execute the query i.

ii.

boolean execute() int executeUpdate()

iii.

ResultSet executeQuery()

Statement

Prepared Statement

Callable Statement

Creating the simple Statement :

Statement st=con.createStatement();

Statement st=con.createStatement(int,int);

Statement st=con.createStatement(int,int,int);

Creating the Prepared Statement :

PreparedStatement ps=con.preparedStatement(String);

PreparedStatement ps=con.prepatedStatement(String,int);

PreparedStatement ps=con.prepatedStatement(String,int,int);

PreparedStatement ps=con.prepatedStatement(String,int,int,int);

Creating the CallableStatement :

CallableStatement cs=con.prepareCall(String);

CallableStatement cs=con.prepareCall(String,int,int);

CallableStatement cs=con.prepareCall(String,int,int,int);

SQL Engine

PL/SQL stored procedure

Statement vs PrepareStatement :

Statement i.

Use the statement to execute single query which gets updates frequently ii.

When you are creating the Statement using connection interfaces create

Statement method, no need to pass the query as a string to that. But you need to pass the query as a string in execute() (or) executeUpdate() (or) executeQuery(). iii.

When you submit a query to the SQL engine using Statement everytime the query will be compiled first and then it will be executed. iv.

Performance wise, Statements are not good enough. v.

Statements st=con.createStatement()

Result rs=st.executeQuery(“select * from abc”);

ResultSet rs1=st.executeQuery(“select * from student”); vi.

We don’t have place holders mechanism in statement

Prepared Statement i.

Use Prepared Statement to execute a single query without updations. ii.

When you are creating the prepared

Staement using connections interface prepareStatement() method you need to pass query as a string and no need to pass the query in execute() or executeUpdate() or executeQuery(). iii.

When you submit the query to SQL engine using PreparedStatement first time the query will be compiled and executed. Second time onwards the query will be executed directly, by sing the pre-compiled query in the first time. iv.

PrepareStatements performance is better than statements. v.

PreparedStatement ps=con.preparedStatement(“select * from abc”);

ResultSet rs=ps.executeQuery();

ResultSet rs1=ps.executeQuery(); vi.

We have place holders mechanism in prepareStatement

 Statement st=con.createStatement();

ResultSet rs=st.executeQuery(“select * from student where sid=”+sid+”);

 PreparedStatement ps=con.prepareStatement(“select * from student where sid=? and email=?(place holder) and phone=?); ps.setInt(1,sid); ps.setString(2,email); ps.setString(3,phone);

Differece among execute(),executeUpdate() & executeQuery() : - execute() i.

Return type is Boolean ii.

i.

ii.

It will return true, if the query exection is successful, otherwise it will return false executeQuery()

Return type is ResultSet i.

It returns no.of rows as a result set fetched from the given table using select statement. executeUpdate()

Return type is int ii.

When the SQL query is executed successfully, it returns no.of records affected in the query.

 execute() method will return true,if the query execution is successful, otherwise it will return false.

 When the query is successfully executed it returns no.of records affected in the query.

Q : Can I pass insert\update\delete statements in executeQuery()

Q : Can I pass select statement to execute() or executeUpdate() method.

Q : What is the return type of execute method when iam passing insert/update/delete/statement.Whose execution completed successfully.

Q : What is the return type of executionUpdate() method when Iam passing delete statement whose execution completed successfully.

Example using Prepared statement with oracle type IV driver. import java.sql.*; class JdbcEx3

{

P s v m (string args[ ])

{

Connection con=null;

PrepatedStatement ps=null,ps1=null; int sid=99;

String sname=”abc”;

String email= abc@sd.com

;

String dob=”01-JAN-2000”; double feebal=9876; try

{

Class.forName(“Oracle.jdbc.driver.OracleDriver”); con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:javaSeshu”,”scott”,

“tiger”); ps=con.prepareStatement(“insert into student values(?,?,?,?)”); ps.setInt(1,sid); ps.setString(2,sname);

ps.setString(3,email0; ps.setDouble(4,feebal); int x=ps.executeUpdate(); if(x==1) else s.o.p(“ok”); s.o.p(“not ok”); ps1=con.prepareStatement(“select * from student”);

ResultSet rs=ps1.executeQuery(); while(rs.next())

{ sid=rs.getInt(1); sname=rs.getString(2); email=rs.getString(3); feebal=rs.getDouble(4); s.o.p(“*”+sid+” “=sname+” “+email+” “+feebal+” “0;

}

}catch(Exception e)

{

e.printStackTrace();

}

Finally

{

Try

{

if(ps!=null)

ps.close(); if(con!=null) con.close();

}catch(Exception e)

{ e.printStackTrace();

} } } }

Example with Callable Statement and Oracle type-IV Driver :

=> T o execute the stored procedures in database.

=> Create or replace procedure P1(a in number, b in number, c out number) as

begin

end c:=a+b;

DButil.java

Public class DButil

{

public static connection getDBConnection()

{

Connection con=null;

Try

{

Class.forName(“Oracle.jdbc.driver.OracleDriver”;

Con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:javaSeshu”,”scott”,”tiger”);

}

Catch(Exception e)

{

e.printStackTrace();

}

Return con;

}

Public static void cleanup(Connection con, Statement s)

{

Try

{

if(con!=null)

con.clsoe(); if(s!=null)

s.close();

}catch(Exception e)

{ e.printStackTrace();

} } }

Jdbc Ex4.java

Package com.javaSeshu.jdbc; import java.sql.*; import com.javaSeshu.util.*; class JdbcEx4

{

P s v m(String a[ ])

{

Connection con=null;

CallableStatement cs=null; try

{

Int a=10 b=20 c=0; con=DBUtil.getDBConnection(); cs=con.prepareCall(“{call p1(?,?,?)}”); cs.setInt(1,a); cs.setInt(2,b); cs.registerOutParameter(3,Types.INTEGER); int x= cs.executeUpdate(); s o p(cs.getInt(3);

}catch(Exception e)

{

e.printStackTrace();

}

Finally

{

DBUtil.cleanup(con,cs);

} } }

Procedure without “out” parameters cs=con.prepareCall(“{call p1(?,?,?)}”); cs.setInt(1,10); cs.setInt(2,20) cs.setInt(3,30); cs.executeUpdate();

Procedure with “out” parameters cs=con.prepareCall(“{call p1(?,?,?,?)}”); cs.setInt(1,10); cs.setInt(2,20); cs.registerOutParameter(3,Types.INTEGER); cs.registerOutParameter(4,Types.DOUBLE); cs.executeUpdate(); x=cs.getInt(3);

DataBase MetaData :

Package com.javaSeshu.jdbc;

Import java.sql.*;

Import com.javaSeshu.util.*; class JdbcEx5

{

P s v m(String args[])

{

Connection con=null;

Statement st=null; try

{

con=DBUtil.getDBConnection();

DatabaseMetaData dbmd=con.getMetaData();

S o p(dbmd.getDatabaseMajorVersion());

S o p(dbmd.supportsTransactions());

S o p(dbmd.getDriverName());

S o p(dbmd.getDriverVersion());

S o p(dbmd.getDriverMajorVersion());

}catch(Execption e)

{

e.printStackTrace();

}

Finally

{

DBUtil.cleanup(con,st); y=cs.getDouble(4);

} } }

ResuiltSets :

ResultSets are java objects which can store multiple row, fetched from database.

 We can devide the ResultSets into 2 categories based on pointer or cursor movement.

1.

Forward only ResulstSets

2.

Scrollable ResultSets

 We can also devide the resultsets in two categories based on accessing capabilities

1.

Read-only ResultSets

2.

Updatable ResultSets

 By default ResultSets are forward only and Read-only.

 Using forward-only resultsets, you can move the cursor in forward direction only using next() method.

 Using scrollable resultsets, you can move the cursor in both forward and reverse directions and also to a specified location.

 When resultset is scrollable, we can apply the following methods. i.

next()

V. alterLast() ii.previous() vi. relative() iii.aAbsolute() vii. first() iv. last() viii. beforeFirst()

IX. isFirst() x. isLast() xi. isBeforeFirst() xii. isAfterLast()

*. Relative(2) -> Move the cursor in the forward directions two positons from the current positin.

*. Relativ9-2) -> Then cursor will move two position in the backward direction from the current position

*. If you update the resultset then automatically database also updated, when the result set is updatable.

=> Using READ_ONLY result sets you can get data from resultset by using get xxx() method provided in

ResultSet interface. But we can not call Update xxx() method on READ_ONLY result sets.

=> Using UPDATABLE resultssets you can update the result set with new values and new values will be updated in database automatically.

Making the result set scrollable and updatable : con. createStatement();->Forward-only, read_obnly st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE.RwsultSet.CONCUR_UPDATABLE);

(now it is scrollable and updatable)

Example for Scrollable ResultSets

Package com.javaSeshu.jdbc; import java.sql.*; import com.javaSeshu.util.*; class JdbcEx6

{

p s v main(String args[])

{

int sid=0;

String sname=null,email=null; double feebal=0;

Connection con=null;

Statement st=null; try

{ cCon=DBUtil.getDBConnection(); st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONKLY);

String sql=”select * from student”;

ResulstSet rs=st.executeQuery(sql);

S o p(“In forward order”); while(rs.next())

{

sid=rs.getInt(1); sname=rs.getString(2); email=rs.getString(3); feebale=rs.getDouble(4); s o p(“*”+sid+” “+sname+” “+” ”+email+” “+feebal);

} rs.absolute(2); s o p(“second row ..”); sid=rs.getInt(); sname=rs.getString(2); email=rs.getString(3); feebal=rs.getDouble(4); s o p(“*”+sid+” “+sanme+” “+email+” “+feebal); rs.afterLast(0; s o p(“reverse order…”); while(rs.previous())

{ sid=rs.getInt(1); sname=rs.getString(2); email=rs.getString(3); feebal=rs.getDouble(4); s o p(“*”+sid+” “+sanme+” “+email+” “+feebal);} if(rs!=null) rs.close();

}

Catch(Exception e)

{

e.printStackTrace();

}

Finally

{

DBUtil.cleanup(con,st);

} } }

Updatable ResultSet

 insert row into RwsultSet

 Update row of ResultSet

 Delete row from ResultSet

*. ResultSets are connection-oriented

Select * from student;

88

77

66

B

C

D

A

B

C

D sid

99

88

77

66

Student sname email

A

B

C

D

A

B

C

D

 When the result set is updatable, the following two things will happened automatically. i.

When you update the resultset, the updation will be notified to the table automatically. ii.

When other user is updating the table, that updation will notified to the ResultSet.

This is for deletion rs.absolute(3); rs.deleteRow();

This is for Updating rs.absolute(2); rs.updateString(2,”BBB”); At this timeupdation is done in result set rs.updateString(3,”Audi”); only rs.updateRow(); -> At this time the updation is done in database.

This is for insertion rs.moveToInsertRow(); rs.updateInt(1,999); rs.updateString(2,”xyz”); rs.updateString(3,”xyzabc.com”); rs.insertRow();

Example for updatable ResultSets package com.javaSeshu.jdbc; import java.sql.*; import com.javaSeshu.util.*; class jdbcEx7

{

P s v main(String args[ ])

{ int sid=0;

String sname=null, email=null; double feebal=0.0;

Connection con=null;

Statement st=null; try

{ con=DBUtil.getDBConnection();

DatabaseMetaData dm=con.getMetaData();

If(dm.supportsresultSetType(ResultSet.CONCUR_UPDATABLE)

{ s o p(“ok”); st=con.createStatement(ResultSet.TYPE_SCROOL-INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

String sql=”select * from student”;

ResultSet rs=st.executeQuery(sql); s o p(“In forward order ….”); while(rs.next())

{

Sid=rs.getInt(1); sname=rs.getString(2); email=rs.getString(3); feebal=rs.getDouble(4); s o p(“*”+sid+”..“+sname+”..”+email+”..”+feebal);

} rs.absolute(1); rs.updateString(2.”sri”); rs.updateString(3,” sri@sd.com

”); rs.updateRow(); rs.absolute(4); rs.deleteRow(); rs.moveToInsertRow(); rs.updateInt(); rs.updateInt(1,55); rs.updateString(2,”abc”); rs.updateString(3,” abc@sd.com

”); rs.insertRow(); if(rs!=null) rs.close();

} catch(Exception e)

{

e.printStackTrace();

}

Finally

{

DBUtil.cleanup(con,st);

} } }

1.setFetchDirection();

2.getFetchDirection();

These two methods are used to specify the fetch direction and get the available fetch direction.

We can use 3 constants for this.

1.FETCH_UNKNOWN

2.FETCH_FORWARD

3.FETCH_REVERSE

=>. setFetchSize() and getFetchSize(), These two methods are available in ResultSet interface and Statement interface also.

=>. setFetchSize() method is used to specify the no.of rows to be fetched from the database at a time.

Batch Updates

 Using BatchUpdates we can submit set of insert or update or delete statements to the sql engine in one request.

/*Example for Batch Updates */ package com.javaSeshu.jdbc; import java.sql.*l import com.javaSeshu.util.*; class JdbcEx8

{ p s v m(String a[ ])

{

String s[][]={{“1”,”1”,”1”,”1”},{“2”,”2”,”2”,”2”},{“3”,”3”,”3”,”3”},{“4”,”4”,”4”,”4”}};

Connection con=null;

Statement st=null;

try

{ con.DBUtil.getDBConnection(); st=con.createStatement();

String sql=null; for(int i=0;i<s.length;i++)

{ sql=”insrt into student values(“”+s[i][0]+” ‘,’ “+s[i][1]+” ‘,’ “+s[i][2]+” ‘,’ “+s[i][3]+” ‘)”; st.addBatch(sql); int z[]=st.exectuteBatch(); for(int i=0;i<z.length;i++)

} s o p(z[i]); catch(Exception e)

{

e.printStackTrace();

}

Finally

{

DBUtil.cleanup9con,st);

} } }

ADVANCED JDBC

We have the following things in advanced JDBC

1.Connection pooling mechanism

2.JDBC Transactions

3.RowSets

=> Sun has provided javar.sql package to implement these advanced topics.

Connection Pooling

When we are using DriverManager connection management we can see two problems. i.

Every time we are creating the connection, after using that we closing it immediately. Creating the connection and destroying the connection every time is very expensive. ii.

We are hardcoding the driver class name, url, username and password in Jdbc program. Later if I migrate the database or drivers I have to modify all the Jdbc programs. This increases the maintenance of the application and decreases the flexibility of system.

We can avoid the above problems by using connection pooling

 Connection poolingis set of Jdbc connections, created by the server(any web server or application server) at server startup.

Installation steps for weblogic 8.1 application server

Step-1 : Double click on Platform811_win32

Step-2 : Click on NEXT

Step-3 : Select yes and click on Next

Step-4 : Provide the bea home directory as D:\bea and click on next.

Step-5 : Install type is “complete” and click on next

Step-6: Don’t change the product installation directory. Just simply click on next.

Step-7 : Uncheck two i.

ii.

Install xml spy

Run quick start and click on done.

Steps to create the weblogic Domain :

Step-1 : Select start -> programs -> bea weblogic platform8.1 -> configuration wizard.

Step-2 : Clcik on next

Step-3 : Select Basic weblogic server domain and click on next.

Step-4 : Click on next.

Step-5 : Provide the username and password and click on next.

Step-6 : Click on next.

Step-7 : Give the configuration name as javaSeshu and click on create.

Step-8 : Click on done.

Configuration JDBC connection pools in weblogic console

1.

Start the weblogic server

Start -> programs -> beaweblogic platforms8.1 -> user_projects -> javaSeshu -> startServer.

2.

Open the browser and type the following in address bar http://localhost : 7001.console (7001 is a port number)

Different servers has different port numbers]

3.

Provide the username and password and click on signin

4.

Click on continue with my current browser(It will not give if the browser is compatable with the driver)

5.

Click on javaSeshu -> Services -> Jdbc -> connection pools

6.

Click on configure a new Jdbc connection pool.

7.

Select the database as “oracle” and driver as “oter” and click on Continue.

8.

Provide connection poolk name as B8pool, and driver class aas oracle.jdbc.driver.OracleDriver and url as

Jdbc:oracle:thin:@localhost:1521:javaSeshu and username as “scott” and password “tiger”, and click on testDriverConfiguration.

9.

Click on create and deploy

Configuring data Sources

Step-1 : javaSeshu ->Services -> jdbc -> DataSources

Step -2 : Click on configure a new Jdbc data Source.

Step -3 : provide name : jdbc/B8pool

JNDI name : jdbc/B8pool and click on Continue.

Step-4 : It will give list of pools. Select B8pool and click on continue.

Step-5 : click on create.

Data Source is the interface in javax,sql (DataSource is the collection of Jdbc connections).

JNDI -> JavaNaming & Directory Interface (JNDI is a Naming Service).

DNS _> Domain Naming Service (DNS is the combination of Domain Name and IP address)

The Domain Name is unique.

Ex : www.javaSeshu.com-198.2.9.99

Binding with

Jdbc\B8 pool

JNDI Name ds

Object bind(). This will be take care by container Look up you have to call manually

 DataSource object is singleton.

Object o=lookup(“jdbc\B8pool”)

 Maximum connections are fixed by server Initially creates n connection.

It can increases the connections depends on the server

 JNDI registry is available in LDAP Server. This will start when weblogic server started.

 Only container can destroy the connection.

Note : JNDI is a registry in which we can bind java object with some name, that name is called as JNDI name.

 We can lookup the object with the JNDI name. Look up and bind() methods are available in context interface of javax.Naming package.

 We have to create the context with the following properties

Properties p=new properties(); p.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.WLInitialContextFactory”); p.put(Context.PROVIDER_URL,”t3://localhost:7001”); here t3 -> is protocol to interact with LDAPServer which is running inside weblogic server.

Context ctx=new InitialContext(p);

Connection Pooling mechanism Example :

1.

Start the weblogic server

2.

Open the weblogic console

3.

Configure the connection pool.

4.

Configure the datasources

5.

Write the program CPMDemo.java import java.util.*; import java.sql.*; import javax.sql.*; import javax.naming.*; calss CDMDemo

{ p s v m(String a[])

{ int sid=0;

String sname=null, email=null; double feebal=0.0; try

{

Properties p=new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.WLInitailContextFactory”); p.put(Context.PROVIDER_URL,”t3://localhost:7001”);

Context ctx=new InitialContext(1);

Object o=ctx.lookup(“jdbc/B8pool”);

DataSource ds=DataSource);

Connection con=ds.getConnection();

Statement st=con.createStatement();

String sql=”select * from student”;

ResultSet rs=st.executeQuery(sql); while(rs.next())

{ sid=rs.getInt(1); sname=rs.getString(2); email=rs.getString(3); feebal=rs.getDouble(4); s o p(“*”+sid+”..”+sname+”..”+email+”..”+feebal);

} rs.close(); st.close(); con.close();

}catch(Exception e)

{

e.printStackTrace();

} } }

6.

Ren SetEnv d:\bea\user.projects\domains\javaSeshu>SetEnv

7.

Compile javac CPMDemo.java

8.

Set classpath=%classpath%;.;

9.

Run as >javaCPMDemo

Transactions :

In J2ee applications we can manage Transactions using following tow API’s.

1.

Jdbc API’s

2.

JTA ( Java Transactions API)

The following are required to manage the transactions in Jdbc.

 ConnectionInterface has the following methods and constants to the transactions int TRANSACTION_NONE; int TRANSACTION_READ_UNCOMMITED; int TRANSACTION_READ_COMMITED; int TRANSACTION_REPEATABLE_READ; int TRANSACTION_SERIALIZABLE; void setAutoCommit(Boolean); boolean getAutoCommit(); void commit(); void rollback(); void setTransactionIsolation(int); int getTransactionIsolation();

Definition : Performing set of Database Operations as a single automic unit is called Transaction.

 Transaction works an all or nothing preposition. i.e if all the operations in the transaction are successful then commit the transaction. If any one operation is failed rollback the transaction(rollback all the database operations)

-> Transaction guarentees ACID properties

A – Automicity

C – Consistency

I – Isolation

D – Durablily

Automocity : - Executing more than one database operations as a single automic unit with all or nothing proposition is called automicity. i.e, whe all the operations in a transactions are successful then issue the commit, any one is failed issue the rollback.

Consistency : - Performing the database operations with system state to be consistent. i.e, perform the database operations without violating the business rules applied.

Isolation : - Running morehtan one transactin concurrently without knowing each other.

Durability : - Protecting the database for a longer period from system crashes or database server crashes or network failures or power failures, etc… Maintain the log file to log the database operations happened in the transaction and recover the database after crashes using the log file.

 When you are running the multiple transactions concurrently we have to control the concurrency of transactions properly. Otherwise we will get the following 3 problems.

1.

Dirty Read Problem

2.

Pepeatable Read Problem.

3.

Phantom Read Problem

1.

Dirty Read Problem : This problem occurs due to reading the uncommitted data. We can solve this by reading the commited data. i.e by locking a particular column.

2.

Repeatable Read Problem : - Some times we can get different set of values in different reads of a database in a single transaction. This problem is called repeatable read problem. We can solve this problem by locking the entire row.

3.

Phantom Read Problem : - Some times we can get different no.of rows in different reads of a database in single transaction. This problem is called phantom Read Problem. We can solve this problem by locking the entire table.

We can solve the above discussed problems by applying the following 4 transactional isolation levels properly.

1.

TRANSACTION_READ_UNCOMMITED

2.

TRANSACTION_READ_COMMITED

3.

TRANSACTION_REPEATABLE_READ

4.

TRANSACTION_SERIALIZABLE

Dirty Read RepeatableRead does not solve does not solve READ_UNCOMMITED

READ_COMMITED solve solve does not solve solve REPEATABLE_READ

SERIALIZABLE solve solve

PhantomRead does not solve does not solve does not solve solve

Two types of locks

1.

Optimistic 2. Pesimistic

 When you are applying the transactional isolation levels, you may hold the lock on either column or a row or some times on table also.

 System uses two types of locking mechanism to hold the locks

1.

Pessimistic locking 2. Optimistic locking

Pesimistic Lock :

T1 Lock

T2

T3

Only can read the data(select)

Optimistic Lock :

Lock They can updata/delete/insert/select

T2

T1

T3

 We can get the currently available transactional isolation levels by calling the following method int getTransactionIsolation()

 We can set required transactional isolation level by the following method

Void setTransactionIsolation(int);

 By default AutoCommit is true i.e after executing the every statement, system issues commit. To stop that disable the auto commit(make auto commit false) as follows. con.setAutoCommit(false); this is the starting of a transaction. After this we can perform more than one database operations and we have to issue the commit or rollback explicitly. try

{ con.setAutoCommit(false); deposit(-,-); withdraw(_,_); con.commit();

}catch(Execption e_

{ con.rollback();

}

RowSets :

RowSet is not an official part of Jdbc. But RowSet addresses problems with the ResultSet

The following are the problems with ResultSet.

1.

resultSet is connection-oriented i.e,,without connection we can not access records in resultset. In web based applications when you have more records it will take more time to access all the records. Keeping the connection for longer time consumes upacceptable amount of resources and degrades the application performance.

2.

Connections taken from DriverManager cannot be serialized (we can serialize connections obtained from data sources). Because of this we can not serialize ResultSet also. For this we need to copy the records from ResultSet to connection-less java object. So that we can pass that connection-less java object. So that we can pass that connection-less java object to a remote mechine without connection.

 RowSet is an interface in javax.sql package which gives the solutions for the above discussed problems… interface RowSet extends ResultSet

{

String getUrl(); void setUrl(String);

String getDataSourceName(); void setDataSourceName(String);

String getUserName(); void setUserName(String);

String getPassword(0; int getTransactionIsolation(int); void setTransactionIsolation(int);

String getCommand(); void setCommand(String); int getMaxFieldSize(0; void setMaxFieldSize(int); int getQueryTimeOut(); void setQueryTimeOut(int);

void setxxx(int, xxx); void clearParameters(); void execute(); void addRowSetListner(RowSetListener); void removeRowSetListner(RowSetListner);

} interface RowSetListner extends EventListner

{

void rowSetChanged(RowSetEvent); void rowChanged(RowSetEvent); void cursorMoved(RowSetEvent);

}

There are 4 types of row sets.

1.

JdbcRowSet -> this is similar to ResultSet connection oriented.

2.

Cached RowSet

3.

WebRowSet Connectionless

4.

Joined RowSet

Jdbc RowSet : is a subclass of RowSet, which isserializable, cleanable and connection-oriented.

Note : No need to create connection object. It will create connection object internally and can communicated.

JdbcResultSet jrs=new JdbcResultSet(); jrs.setUrl(“jdbc:mysql://localhost/sridb”); jrs.setUserName(“root”); jrs.setPassword(“javaSeshu”); jrs.setCommand(“select 8 from student”);

:

: jrs. Execute();

whiel(jrs.next())

{

//get all the fields

}

Cached RowSet : it is also a subclass of RowSet which is serializable, clonable and connectionless.

CachedRowSet crs=new CachedRowSet(); crs.setUrl(“jdbc:mysql://localhost/sridb”); crs.setUserName(“root”); crs.setPassword(“javaSeshu”); crs.setCommand(“select * from student”);

:

: crs.execute();

}

While(crs.next())

{

//get all fields

Joined RowSet:

JdbcRowSet jrs=new JdbcRowSet();

CatchedRowSet crs=new CatchedRowSet();

JoinedRowSet rs=new JoinedRowSet(); rs.populate(jrs); rs.populate(crs);

 Populate() method is used to pass the records from ResultSet to Cached/JdbcRowSet.

Ex: ResultSet rs=st.executeQuery(“select * from student”);

CachedRowSet crs=new CachedRowSet();

crs.populate(rs);

 Stand alone java program/application void main()

{

…………………..

…………………

}

 Client/server application

Here we are using java.net package. some client part of application client server

SERVLETS some part of application

Web application

Here we are using Jsp/Sevlets

Web browser client web server web browser client

Client/Server Application Vs WebBased Application server complete application

Client/Server Application Webbased Application

HTML i.

ii.

iii.

iv.

JavaScript

In this we have to divide the application into two parts. One part you have to install in the server machine. Another part you have to install in client machine.

When you modify the application you have to reinstall the client s/w in all the client machines.

We can use c, c++, jave etc.. to develop client/server application

There is a limit for client/server application interms of accessibility

Web Client

Any web browser

IE

NN

Opera

Mozilla i.

We place the entire application in the server itself, and the client access this application with the help of webbrowser ii.

When you modify the application no modifications in the client machines. iii.

We can use Servlets, Jsp, Asp, perlScript etc. to develop the web application. iv.

Web based application is unlimited

Web server

Tomcat

Any application Server

I IS

PWS

Etc…

Application Servers : (web Servers + some extra features)

Web Sphere Web ligic

JBass e-matrix pramathi  (Indian server) JRun

Oracle 9i

IIS – Internet Information Server

PWS – Personal Web Server

Installation steps from Tomcat : (8080 default portnumber)

Step-1 : Make sure that j2sdk is installed in your machine and path, class paths setted and is running properly.

Step-2 : Double click on Jakarta_tomcat_5.0.16

Step-3 : Click on next

Step-4 : Click on I Agree

Step -5 : Click on next

Step-6 : Choose the installation Location to d:\tomcat5.0\and click next

Step-7 : port : 8080

UserName : javaSeshu

Password : AudiSeshu and click next

Step-8: Click on install

Step-9 : Uncheck two options and click on finish

Step-10 : Start the server

Start -> programs -> apacheTomcat 5.0 -> start Tomcat

Step-11 : Opent the browser and type the following http://localhost/8080

Simple Example :

Step 1 : Write the hello.html

<html><head></head>

<body><font color=”red”>

<h1>Welcome to Java</h1>

</font></body>

</html>

Step 2 : Copy to d:\tomcat5.0\webapps\ROOT

Step 3 : Open the browser and type http://localhost:8080/hello.html

Web Server i.

Webserver has web container which gives the support for web components called Servlets and JSPs ii.

Ex. Tomcat, Resin iii.

Services of webcontainer i.

Networking ii.

Threading iii.

Streams iv.

Declarative security v.

JSP support vi.

Resource management

Application Server i.

Application Server has two containers. One is web container and second is EJB container.

Web container supports Servlets JSPs, EJB container supports EJB Components. ii.

Ex : Oracle9i, JBoss, JRun, Orien, Pramathi etc iii.

Services of EJB Container i.

Networking ii.

Threading low level services iii.

Streams iv.

Resource management v.

Transaction management middle vi.

Security level vii.

Persistant services viii.

Timer service ix.

Web services

Web Browser http://www.javaSeshu.com

http request

Head

Body

http response

Web Server

Web Container httpRequest Header Contains

Head

Body

Host : http://www.javaSeshu.com

IP address : 198.9.27.3

 In www we are using http protocol to send the request and to receive the responses.

 Web browser is an application which you have to use to send a request to the webserver and to receive the response from the webseerver.

 Web Server is an application which is used to receive the requests from web client and processing the request to send the response to the web client.

 Http protocol makes the communication between web browser and web server.

 The request we are sending using http protocol is called http request and has two parts.

1.

Http request header

2.

Http request body

 Response we are getting using http protocol is called http response has two parts.

1.

Http response header

2.

Http response body

 http protocol is stateless protocol i.e., it does not maintain clients conversational state i.e.. it won’t remember what happened in the previous request.

 http is build upon TCP/IP

 TCP is responsible to control the transmission of the data from one machine to another machine, and IP is responsible to carry the data from one machine to another machine.

First.html Web Server

WELCOME TO JAVA

ENTER NAME :

Web Container

First Servlett

SUBMIT

//first Servlet Example

1.first.html

<html><body><center>

<u><font color=”blue” size=5>

WELCOME TO JAVA

</font></u>

<form action=”/Seshu.do”>

Enter Name<br>

<input type=”text” name=”cname”><br>

<input type=”submit” value=”SUBMIT”>

</form></body></html>

2.FristServlet.java

Package com.javaSeshu;

Import javax.Servlet.http.*;

Import javax.Servlet.*;

Import java.io.*;

Public class FirstServlet extends HttpServlet

{

Public void Service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletExceptin

{

//take the data(1).

String cname=req.getParameter(“cname”);

//Process(2)

Cname=”Hello”+cname+”welcome to Servlets”;

//send response(3)

Res.setContentType(“text/html’);

PrintWriter out=res.getWriter();

Out.println(cname);

Out.close();

} }

3.Write the following tags in web.xml(DD)

<servlet>

<servlet_name>first</servlet_name>

<servlet_class>com.javaSeshu.FirstServlet</sevlet_class>

</servlet>

<servlet_mapping>

<servlet_name>first</servlet_name>

<url_pattern>/seshu.do</url_patter>

</servlet_mapping>

4.Compile the Servlet a). Set the class path for servlet_api.jar c:\tomcat5.0\common\lib b). javc_d.*.java

Depending Steps

5.

Copy the first.html to webapps\root\

6.

Copy the com folder to Root\web_INF\classes

7.

Update the web.xml

Running

8.

Start the tomcat

9.

Open the I.E and type the following http://localhost:8080/first.html

Directory Structure of Web application

Webapp name

(Root)

WEB_IN

F

*.jsp *.html *.gif

Web.xml classes lib tlds

*.class *.jar *.tld

-> Root is the default webapp name, which is created by the tomcat at the time of installation.

Download