5th Unit Java

27
JAVA & J2EE 10IS753 Dept. of ISE, MIT-Mysore Page 1 UNIT-5 JDBC J2SE AND J2EE : Java 2 standard edition is the original edition of java and it consist of application programming interfaces (API) needed to build java application or applet. J2EE: java 2 enterprise edition is the enhanced version of J2SE, it has the API to build applications for a multi- tier architecture. CONCEPT OF JDBC: JDBC driver to be a translator that converted low level proprietary DBMS messages to low level messages understood by the JDBC API and vice versa. The high level data objects defined in the JDBC API to write a routine that interacted with the DBMS. JAVA data objects convert the routine into low-level messages that conform to the JDBC driver specification and send them to the JDBC driver. The JDBC driver translates the routine into low-level messages that are understood and processed by the DBMS. JDBC driver open a connection between the DBMS and the J2EE component. Translate low-level equivalents of SQL statements sent by the J2EE component into messages that can be processed by the DBMS. Return data that conforms to the JDBC specification to the JDBC driver. Return information such as error messages that conforms to the JDBC specification to the JDBC driver. Provide transaction management routines that conform to the JDBC specification. Close the connection between the DBMS and the J2EE component.

Transcript of 5th Unit Java

Page 1: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 1

UNIT-5 JDBC

J2SE AND J2EE :

Java 2 standard edition is the original edition of java and it consist of

application programming interfaces (API) needed to build java application

or applet.

J2EE: java 2 enterprise edition is the enhanced version of J2SE, it has the API

to build applications for a multi- tier architecture.

CONCEPT OF JDBC:

JDBC driver to be a translator that converted low level proprietary DBMS

messages to low level messages understood by the JDBC API and vice

versa.

The high level data objects defined in the JDBC API to write a routine

that interacted with the DBMS.

JAVA data objects convert the routine into low-level messages that

conform to the JDBC driver specification and send them to the JDBC

driver. The JDBC driver translates the routine into low-level messages

that are understood and processed by the DBMS.

JDBC driver open a connection between the DBMS and the J2EE

component.

Translate low-level equivalents of SQL statements sent by the J2EE

component into messages that can be processed by the DBMS.

Return data that conforms to the JDBC specification to the JDBC driver.

Return information such as error messages that conforms to the JDBC

specification to the JDBC driver.

Provide transaction management routines that conform to the JDBC

specification.

Close the connection between the DBMS and the J2EE component.

Page 2: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 2

JAVA DATABASE CONNECTIVITY:

Whenever the java needs to connect to the database first it should obtain

the driver.

Java is a frontend tool.

Database is a backend tool.

The drivers are database, image, picture, sound drivers etc

These drivers are available in a class called "DriverManager".

The database driver is "sun.Jdbc.Odbc.JdbcOdbcdriver" . This is in the

form of "dll" (dynamic link library).

Once the driver is obtained then java can connect to the database.

Once the connection is established then java can issue “SQL"

statements.

These "SQLs" are insertion, deletion, updation, extraction etc.

If the SQL is of extraction then the matched records are retrieved from

the

"ResultSet”. It is an interface.

Then from the "ResultSet" records are retrieved and displayed.

If the SQL is of insertion, deletion and updation then “ResultSet" is not

required.

Data source name (DSN): It points exactly to the particular database

name.

Properties of JDBC Drivers:-

Open a connection between the DBMS and J2EE component.

Translate low-level equivalents of SQL statements sent by the J2EE component

into messages that can be processed by the DBMS.

Return data that conforms to the DBMS specification to the JDBC driver.

Return information such as error messages that conforms to the JDBC

specification to the JDBC driver.

Provide transaction management routines that conform to the JDBC

specification.

Close the connection between the DBMS and the J2EE component.

Page 3: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 3

JDBC DRIVER TYPES

TYEP1 JDBC-ODBC Bridge

TYPE2 JAVA / NATIVE CODE DRIVER

TYPE 3 JDBC DRIVER

TYPE4 Native-Protocol pure Java Driver

TYPE1 JDBC-ODBC BRIDGE:

It can also be called as JDBC-to-ODBC driver. It is used to translate

DBMS calls between the JDBC specification and the ODBC specification.

This driver receives the messages from a J2EE component that conforms

to the JDBC specifications.

These messages are translated by this driver into the ODBC message

format which in turn translated into the message format understood by

the DBMS.

In a type1 driver, a JDBC Bridge is used to access ODBC drivers

installed on each client machine. Using ODBC requires configuring on

system a data source name that represents the target database.

It is a java soft bridge product that provides JDBC access via ODBC

drivers.

TYPE 2 JAVA / NATIVE CODE DRIVER

This driver uses java classes to generate platform - specific code, that

code is understood by a specific DBMS.

The disadvantage of this using this driver is the loss of some portability

of code.

JDBC API calls are converted into native C/C++ API calls which are

unique to the database.

TYPE3 JDBC DRIVER

It is also referred to as the java protocol. It is the most commonly used

JDBC driver. This driver converts SQL queries into JDBC formatted

statements.

Page 4: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 4

This again translated into the format required by the DBMS.

Three tier approach is used to accessing databases. The JDBC clients

use standard network sockets to communicate with a middleware

application server.

The socket information is then translated by the middleware application

server into the call format required by the DBMS, and forwarded to the

database server.

TYPE4 JDBC DRIVER

It is also known as database protocol. This is similar to type3 JDBC

driver except SQL queries are translated into the format required by the

DBMS.

It is a pure java based driver that communicates directly with database

through socket connection.

JDBC PACKAGES:

The JDBC API contained in two packages.

The first package is called java.sql and contains core java data objects

of the JDBC API.

These include java data objects that provide basics for connecting to the

DBMS and interacting with data stored in the DBMS.

The other package contains the JDBC API is the javax.sql. It extends

java.sql and it is in J2EE.

Java data objects that interact with the Java Naming and Directory

Interface (JNDI). It manages connection pooling.

OVERVIEW OF JDBC PROCESS:

Loading the JDBC driver

Connecting to the DBMS

Creating and executing a statement

Processing data returned by the DBMS

Terminating the connection with the DBMS

Page 5: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 5

LOADING THE JDBC DRIVER:

The JDBC driver must be loaded before the J2EE component can connect to

the DBMS.

class.forName("sun.JDBC.odbc.JDBCOdbcDriver")

class.forName() method is used to load the JDBC driver.

Connecting to the DBMS:

Once the driver is loaded, the J2EE component must connect to the

DBMS using DriverManager.getConnection() METHOD.

DriverManager is the highest class in the java.sql hierarchy and is

responsible for managing driver information.

This method returns a connection interface that is used throughout the

process to reference the database.

Create and execute a SQL statement:

After loading the driver and connection is established with a particular

database managed by the DBMS, is to send a SQL query to the DBMS for

processing. SQL query consist of SQL commands.

createStatement() method is used to create a statement object.

The statement object is then used to execute a query and return a

ResultSet object that contains the response from the DBMS.

Processing the data returned by the DBMS:

ResultSet object is assigned the results received from the DBMS after the

query is processed. ResultSet object consists of methods used to interact

with data that is returned by the DBMS to J2EE component.

The first time that the next() method of the ResultSet is called , then the

pointer is positioned at the first row in the ResultSet.

The getString() method of the ResultSet object is copy the value of a

specified column in the current row of the resultset to a string object.

Terminate the connection to the DBMS:

The connection to the DBMS is terminated by using the close() method of the

connection object once the J2EE component is finished accessing the DBMS.

Page 6: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 6

DATABASE CONNECTION:

JDBC driver is loaded and registered with the DriverManager.

J2EE component connects with the JDBC driver that is associated with

the DBMS.

The purpose of the loading and registering the JDBC driver is to bring the

JDBC driver into the Java Virtual Machine (JVM).

class.forName() method is used to load the JDBC driver.

JDBC/ODBC Bridge is the driver that is being loaded.

THE CONNECTION

The URL consists of three parts. These are

jdbc which indicates the JDBC protocol is to be used to read the URL.

<sub protocol> which is the JDBC driver name.

<subname> which is the name of the database.

The types of connection methods:-

After the JDBC driver is successfully loaded and registered the J2EE

component must connect to the database.

The connection to the database is established by using one of the three

getconnection() method of DriverManager object.

A connection object is returned by the getConnection() method if access

is generated; otherwise getConnecton method throws SQLException.

Sometimes the DBMS grants access to a database to anyone. In this case

the J2EE component uses the getConnection(String url) method.

One parameter is passed to the method because DBMS only needs the

database identified.

String url=”jdbc:odbc:customerInformation”;

Statement DataRequest;

Connection Db;

Page 7: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 7

try

{

class.forName(“sun.jdbc.odbc.JDBCODBCDriver”);

Db=DriverManager.getConnection(url);

}

catch(ClassNotFoundException error)

{

System.err.println(“unable to load JDBC/ODBC bridge”,er+erroe);

System.exit(1);

}

catch (SQLException error)

{

System.err.println(“cannot connect to the database:”,+error);

System.exit(2);

}

Other databases limit access to the authorized users & require the J2EE

to supply a userid & password with the request to access the database.

In this case, the J2EE component uses the getConnection (string url,

string userid, string password) method.

String url=”jdbc:odbc:customerInformation”;

Statement DataRequest;

Connection Db;

try

{

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

Db=DriverManagergetConnection(url, userid, password);

}

catch (ClassNotFoundException error)

{

System.err.println(“unable to load JDBC/ODBC bridge”,er+erroe);

System.exit(1);

Page 8: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 8

}

catch (SQLException error)

{

System.err.println(“cannot connect to the database:”,+error);

System.exit(2);

}

There might be chances where a DBMS requires information besides the

userid & password before the DBMS grants access to the database. This

additional information is called properties & must be associated with

properties object.Properties used to access a database are stored in a text

file.

The J2EE component uses a FileInputStream object to opoen the file &

the uses the properties object load () method to copy the properties into

properties object.

Associating the JDBC / ODBC bridge with the database :

This is creation of "data source name " (dsn).

Start----settings---controlpanel---administrative tools---- data sources

odbc-----user dsn----add button---select the driver ----next-----enter the

data source name ex: db25---------click next button and click finish

button.

Select "select button" select the database name and click ok button.

Connection pool:-

A connection pool is a collection of database connections that are opened once

and loaded into memory so these connections can be reused without having to

reconnect to the DBMS.

There are two types of connections made to the database. The first is the

physical connection, which is made by the application server using

PooledConnection objects. PooledConnection objects are cached and reused.

The other type of connection is the logical connection. A logical connection is

made by a client calling the DataSource.getConnection() method, which

Page 9: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 9

connects to a PooledConnection objects that already has a physical connection

to the database.

A connection pool is accessible by using the Java Naming and directory

Interface(JNDI).

JNDI provides a uniform way to find and access naming and directory services

independent of any specific naming or directory service.

Context ctext = new InitialContext();

DataSource pool = (DataSource)

ctext.lookup(“java:/cmp/env/jdbc/pool”);

Connection Db = pool.getConnection();

//place code to interact with the database here

Db.close();

Table: - Connecting to a database using a pool connection.

First J2EE component must obtain a handle to the JNDI context, which is

shown in the first statement in the above code segment.

Next, the JNDI lookup() method is called and is passed the name of the

connection pool, which returns the DataSource object called pool.

The getConnection() method of the DataSource object is then called. The

getConnection() returns the logical connection to the database, which is used by

the J2EE component to access the database.

The close() method of the DataSource object is called once when the J2EE

component is finished accessing the database. The close() method closes the

logical connection to the database and not the physical database connection.

This means that same physical connection can be used by the next J2EE

component that needs access to the database.

Page 10: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 10

STATEMENT OBJECTS:-

There are 3 types of statement objects used to execute the query these

objects are

1. Statement Object which execute a query immediately.

2. PreparedStatement object which is used to execute a compiled

query.

3. CallableStatement object which is used to execute store

procedures.

THE STATEMENT OBJECT

The statements object is used whenever a J2EE component needs to

immediately execute a query without first having the query compiled.

The statement object contains the execute Query () method.

The executeQuery () method returns one ResultSet object that contains

rows, columns and metadata that represent data requested by query.

The ResultSet object also contains methods that are used to manipulate

data in the ResultSet.

The executeUpdate() method is used to execute queries that contain

UPDATE and DELETE SQL statements which changes values in a row

and removes a row respectively.

The executeUpdate() method returns an integer indicating the number

Of rows that were updated by the query.

The executeUpdate() is used to INSERT,UPDATE,DELETE and DDL

statements.

import java.SQL.*;

class JDBC60

{

public static void main(String v[])throws SQLException

{

Statement DataRequest;

Page 11: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 11

ResultSet Results;

Connection Db=null;

try

{

Class.forName("sun.JDBC.odbc.JDBCOdbcDriver");

Db = DriverManager.getConnection("JDBC:odbc:db100");

}

catch(ClassNotFoundException error)

{

System.err.println("unable to load the JDBC/odbc bridge "+error);

System.exit(1);

}

catch(SQLException error)

{

System.err.println("cannot connect to the database"+error);

System.exit(2);

}

try

{

String query="select * from emp";

DataRequest=Db.createStatement();

Results=DataRequest.executeQuery(query);

while(Results.next())

{

System.out.println("empno="+Results.getString("empno"));

System.out.println("empname="+Results.getString("empname"));

System.out.println("empsal="+Results.getString("empsal"));

}

DataRequest.close();

}

catch(SQLException error)

{

System.err.println("SQL error "+ error);

Page 12: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 12

System.exit(3);

}

Db.close();

}

}

PreparedStatement OBJECT:

A SQL query can be precompiled and executed by using the

preparedStatement object. A question mark is used as a placeholder

for a value that is inserted into the query after the query is compiled.

It is this value that changes each time query is executed.

EX: String query= "select * from customer where custnumber = ? ";

It is used to use the SQL statements many times. It accepts input

parameters at runtime.

import java.SQL.*;

class JDBC62

{

public static void main(String v[])throws SQLException

{

Statement DataRequest;

ResultSet Results;

Connection Db=null;

try

{

Class.forName("sun.JDBC.odbc.JDBCOdbcDriver");

Db = DriverManager.getConnection("JDBC:odbc:db100");

}

catch(ClassNotFoundException error)

{

System.err.println("unable to load the JDBC/odbc bridge "+error);

System.exit(1);

}

catch(SQLException error)

Page 13: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 13

{

System.err.println("cannot connect to the database"+error);

System.exit(2);

}

try

{

String query="select * from emp where empno=?";

PreparedStatement pstatement=Db.preparedStatement(query);

//pstatement.setString(1,"123");

Results=pstatement.executeQuery();

pstatement.close();

}

catch(SQLException error)

{

System.err.println("SQL error "+ error);

System.exit(3);

}

Db.close();

}

}

Callable statement:

This object is used to call a stored procedure from within a J2EE

object. A stored procedure is a block of code and it identified by a

unique name.

The stored procedure is executed by invoking the name of the stored

procedure.

This object uses three types of parameters when calling a stored

procedure.

These parameters are IN, OUT and INOUT.

IN: data needs to be passed as a parameter to the stored procedure.

OUT: contains the value returned by the stored procedures.

INOUT: It is single parameter that is used to both pass information to

Page 14: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 14

the stored procedure and retrieve information from a stored

procedure.

It is used to access database stored procedures. This interface can

also accept runtime input parameters.

import java.SQL.*;

class JDBC63

{

public static void main(String v[])throws SQLException

{

Statement DataRequest;

ResultSet Results;

Connection Db=null;

String lastordernumber;

try

{

Class.forName("sun.JDBC.odbc.JDBCOdbcDriver");

Db = DriverManager.getConnection("JDBC:odbc:db100");

}

catch(ClassNotFoundException error)

{

System.err.println("unable to load the JDBC/odbc bridge "+error);

System.exit(1);

}

catch(SQLException error)

{

System.err.println("cannot connect to the database"+error);

System.exit(2);

}

try

{

String query="{ CALL lastordernumber(?))";

CallableStatement cstatement=Db.prepareCall(query);

cstatement.registerOutParameter(1,Types.VARCHAR);

Page 15: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 15

cstatement.execute();

lastordernumber=cstatement.getString(1);

cstatement.close();

}

catch(SQLException error)

{

System.err.println("SQL error "+ error);

System.exit(3);

}

Db.close();

}

}

RESULTSET

Data in a ResultSet is logically organized into a virtual table consisting of

rows & columns.

ResultSet object contains metadata such as columns names, column size

& column data type.

The ResultSet uses a virtual cursor to point to a row of the virtual table.

The next() method of the ResultSet object return a Boolean value true if

the row contained data otherwise a Boolean value false is returned

indicating that no more rows present in the ResultSet.

The next() method of the ResultSet is called to move the virtual pointer to

the first row in the ResultSet.

If the is a data in that row the next() returns a true.

getString() method is called to retrieve values in the 1st & 2nd columns of

the ResultSet.

READING THE RESULTSET:-

String url=”jdbc:odbc:customerinformation”;

String userid=”jim”;

String passwd=”keogh”;

String printrow;

Page 16: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 16

String fname;

String DataRequest;

ResultSet results;

Connection Db;

string query=”select fname, lname from customers”;

try

{

class.foName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Db=DriverManager.getconnection(url,userid,passwd);

DataRequest=Db.createstatement();

Results=DataRequest.executeQuery(query);

}

boolean Records=recults.next();

if(!Records)

{

System.out.println(“no data returned”);

System.exit(4);

}

do

{

fname = Results.getstring(1);

lname = result.getstring(2);

printrow = fname + ” “ +lname”;

System.out.println(printrow);

}while(Results.next());

DataRequest.close();

}

Catch(SQLException err)

{

System.err.println(“Data display error”+error);

System.exit(5);

}

Catch(classNotFoundException error)

{

System.err.println(unable to load JDBC/ODBC bridge”+erroe);

System.exit(1);

}

}

Page 17: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 17

UPDATABLE RESULTSET:-

There are 3 ways in which a ResultSet can be changed.

These are updating values in z row deleting a row, and inserting a new

row.

UPDATE RESULTSET:-

Once the executeQuery () method of the statement object returns a

ResultSet the updatexxx () method is used to change the values of a

columns in the current row of the ResultSet.

The xxx in the updatexxx() method is replaced with the data type of the

column that in to be updated.

Updatexxx() method requires two parameters the first is either the

number or name of the column of the ResultSet that is being updated &

second parameter in the value that will replace the value in the column

of the ResultSet.

The value in a column of the result can be replaced with a NULL value by

using updateNULL () method.

The updateNULL () method requires one parameter which is the number

of the column in the current ResultSet.

The updateRow () method is called after all the updatexxx() method are

called.

updateRow() method changes the valued in columns of the current row of

the ResultSet.

String url=”jdbc:odbc:customerinformation”;

String userid=”jim”;

String passwd=”keogh”;

String printrow;

String fname;

String DataRequest;

ResultSet Results;

Connection Db;

Page 18: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 18

string query=”select fname, lname from customers where

fname=’mary’ and lastname=smith”;

try

{

class.foName(“sun.jdbc.odbc.JDBCODBCDriver”);

Db=DriverManager.getconnection(url, userid, passwd);

DataRequest=Db.createstatement(ResultSet.CONCUR_UPDATABLE);

Results=DataRequest.executeQuery(query);

}

boolean Records=recults.next();

if(!Records)

{

System.out.println(“no data returned”);

System.exit(4);

}

try

{

Results.updateString(“ lname“,”smith”);

Results.updateRow();

DataRequest.close();

}

Catch(SQLException err)

{

System.err.println(“Data display error”+error);

System.exit(5);

}

Catch(classNotFoundException error)

{

System.err.println(unable to load JDBC/ODBC bridge”+erroe);

System.exit(1);

}

}

Page 19: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 19

Delete row in the ResultSet:-

The deleteRow() method is used to remove a row from a ResultSet.

The deleteRow() is passed an integer that contains the number of the row to be

deleted.

Results.deleteRow(0); //deletes 0th row in the resultset

Insert row in the ResultSet:-

Inserting a row into the resultset is accomplished using basically the same

technique as is used to update the resultset.

The updateXXX() method requires two parameters. The first parameter is either

the name of the column or the number of the column of the resultset.

The second parameter is the new value that will be placed in the column of the

resultset.

The datatype of the column replaces the xxx in the method name.

The insertRow() method is called after the updateXXX() methods, which causes

a new row to be inserted into the ResultSet.

String url=”jdbc:odbc:customerinformation”;

String userid=”jim”;

String passwd=”keogh”;

String printrow;

String fname;

String DataRequest;

ResultSet Results;

Connection Db;

string query=”select fname, lname from customers”;

try

{

class.foName(“sun.jdbc.odbc.JDBCODBCDriver”);

Db=DriverManager.getconnection(url, userid, passwd);

DataRequest=Db.createstatement(CONCUR_UPDATABLE);

Results=DataRequest.executeQuery(query);

}

Page 20: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 20

boolean Records=recults.next();

if(!Records)

{

System.out.println(“no data returned”);

System.exit(4);

}

try

{

Results.updateString(1,”Tom”);

Results.updateString(2,”smith”);

Results.insertRow();

DataRequest.close();

}

Catch(SQLException err)

{

System.err.println(“Data display error”+error);

System.exit(5);

}

Catch(classNotFoundException error)

{

System.err.println(unable to load JDBC/ODBC bridge”+erroe);

System.exit(1);

}

Page 21: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 21

SCROLLABLE RESULTSET:-

There are 6 methods of the ResultSet object that are used to position the

virtual cursor. They are first(), last(), previous(), absolute(), relative(), and

getRow().

The first() method moves the virtual cursor to the first row in the

ResultSet.

last() method moves the virtual cursor to the last row in the ResultSet.

Previous() method moves the virtual cursor to the previous row.

The absolute() method positions the virtual cursor at the row number

specified by the integer passed as a parameter to the absolute() method.

The relative() method moves the virtual cursor specified number of rows

contained in the parameter.

The parameter is a positive or negative integer where the sign represents

the direction the virtual cursor is moved.

For example, -4 moves the virtual cursor back four rows from the current

row, likewise, 5 moves the virtual cursor forwards 5 row’s from the

current row.

getRow() method returns an integer that represents the current row in

the ResultSet.

The statement object that is created using the createStatement() of the

connection object must be set up to handle a scrollable resultset by

passing the createStatement() method one of three constants.

These constants are TYPE_FORWARD_ONLY,

TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE.

The TYPE_FORWARD_ONLY constant restricts the virtual cursor to

downward movement, which is default setting,

The TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE

constants permit the virtual cursor to move in both directions.

String url=”jdbc:odbc:customerinformation”;

String userid=”jim”;

Page 22: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 22

String passwd=”keogh”;

String printrow;

String fname;

String DataRequest;

ResultSet Results;

Connection Db;

string query=”select fname, lname from customers”;

try

{

class.foName(“sun.jdbc.odbc.JDBCODBCDriver”);

Db=DriverManager.getconnection(url, userid, passwd);

DataRequest=Db.createstatement(TYPE_SCROLL_INSENSITIVE);

Results=DataRequest.executeQuery(query);

}

boolean Records=recults.next();

if(!Records)

{

System.out.println(“no data returned”);

System.exit(4);

}

do

{

Results.first();

Results.last();

Results.previous();

Results.absolute(10);

Results.relative(-2);

Results.relative(2);

fname = Results.getstring(1);

lname = Result.getstring(2);

printrow = fname + ” “ +lname”;

System.out.println(printrow);

}while(Results.next());

DataRequest.close();

}

Catch(SQLException err)

{

System.err.println(“Data display error”+error);

Page 23: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 23

System.exit(5);

}

Catch(classNotFoundException error)

{

System.err.println(unable to load JDBC/ODBC bridge”+erroe);

System.exit(1);

}

METADATA: - Metadata is the data about data.

In databases, metadata describes the structural components of tables

and their elements.

J2EE component can access metadata by using the DatabaseMetadata

interface.

The DatabaseMetadata interface is used to retrieve information about

databases, tables, columns and indexes among other about the DBMS

A J2EE component retrieves metadata about the database by calling the

getdata() method of the connection object.

The getMetadata() method returns a DatabaseMetadata object that

contains information about the database and its component.

Some of the more commonly used DatabaseMetadata object methods are:

getDatabaseProductName():-Returns the product name of the database.

getUserName():- Returns the username.

getURL():- Returns the URL of the database.

getSchemas():-Returns all the schemas names available in this

database.

getPrimaryKey():-Returns primary key.

getProcedures():-Returns stored procedures names.

getTables():-Returns name of the tables in the database.

In databases, metadata an element could include data types, names of data,

size, length of the field, number of columns.

Page 24: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 24

RESULTSET METADATA:-

There are two types of metadata that can be retrieved from the DBMS.

These are metadata that describes the database & metadata that

describes the ResultSet.

Metadata that describes the ResultSet is retrieved by calling the

getMetadata() method of the ResultSet object this returns a

ResultSetMetadata object.

ResultSetMetadata rm = Result.getMetadata ();

Once the ResultSetMetadata is retrieved, the J2EE component can call

method of the ResultSetMetadata object to retrieve specific kind of

metadata, the most commonly called methods are:

getColumnCount():-Returns the number of the columns contained in the

table.

getColumnsName(int Number):- Returns the name of the columns

specified by the column number.

getColumnType(int number):- Returns the data type of the specified by

the column number.

DATA TYPES:

CHAR String

VARCHAR String

LONGVARCHAR String

NUMERIC java.math.BigDecimal

DECIMAL java.math.BigDecimal

BIT Boolean

INTEGER Integer

REAL float

DOUBLE double

DATE java.SQL.date

TIME java.SQL.Time

Page 25: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 25

EXCEPTIONS

Three kinds of exceptions thrown by JDBC methods they are

SQLExceptions

SQLWarnings

DataTruncation

SQLExceptions:

Specify common SQL syntax error in the query and are thrown by many

of the methods contained in java.SQL package.

SQLWarnings throws warnings received by the connection from the

DBMS.

Whenever data is lost due to truncation of the data value, data

truncation exception is thrown.

Transaction processing:

A database transaction consists of a set of SQL statements, each of

which must be successfully completed for the transaction to be

completed. If one fails, SQL statements that executed successfully up to

that point in the transaction must be rolled back.

The commit() must be called regardless if the SQL statement is part of a

transaction or not.

Autocommit feature is by default set to true for comitting automatically.

//program update records

import java.SQL.*;

class JDBC50

{

public static void main(String v[])

{

Statement s1,s2;

Connection con=null;

Page 26: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 26

try

{

Class.forName("sun.JDBC.odbc.JDBCOdbcDriver");

con = DriverManager.getConnection("JDBC:odbc:db300");

}

catch(ClassNotFoundException error)

{

System.err.println("unable to load the JDBC/odbc bridge "+error);

System.exit(1);

}

catch(SQLException error)

{

System.err.println("cannot connecto the database"+error);

System.exit(2);

}

try

{

con.setAutoCommit(false);

String query1="update emp set empsal=15750 where empno=200";

String query2="update emp set empsal=18025 where empno=300";

s1=con.createStatement();

s2=con.createStatement();

s1.executeUpdate(query1);

s2.executeUpdate(query2);

con.commit();

s1.close();

s2.close();

con.close();

}

catch(SQLException ex)

{

System.err.println("SQLexception "+ ex.getMessage());

if(con !=null)

Page 27: 5th Unit Java

JAVA & J2EE 10IS753

Dept. of ISE, MIT-Mysore Page 27

try

{

System.err.println("transaction is being rolled back");

con.rollback();

}

catch(SQLException e)

{

System.out.println(e.getMessage());

}

}

}

}