Você está na página 1de 47

05/24/08 07:03:47

Article
Home> Articles > Java > Database

JDBC Tutorial

This is a JDBC tutorial that explains Java Database Connectivity(JDBC) and defines how a java program can
communicate with a database. JDBC API has two major packages java.sql and javax.sql. JDBC architecture consist of
different layers and drivers which are capable of working with any database. We hope you enjoy working through our
exclusive JDBC tutorial.

1/47
05/24/08 07:03:47
Introduction To JDBC

Introduction To JDBC

Java Database Connectivity(JDBC) defines how a java program can communicate with a database. JDBC API has two
major packages java.sql and javax.sql. JDBC architecture consist of different layers and drivers which are capable of
working with any database

Types Of Drivers As shown above there are 4 types of JDBC drivers available.

1. JDBC-ODBC Bridge:- The driver converts JDBC calls to the ODBC calls which actually interacts with the
database. The client should have the ODBC libraries for this driver.
2. Native API- Partly Java driver:- The driver converts JDBC calls to database specific calls. In order to use the
driver the client should have database libraries.
3. JDBC-Net-All Java:- This driver passes the JDBC calls to proxy server which communicates with the database.
4. Native protocol- All Java:- The driver does not require anything and directly calls the database. This driver is the
fastest among all the four drivers.

Steps to write JDBC programs

The following steps are required to write any JDBC specific programs in java.

1. Load or register the driver with Class.forName().


2. Establish Connection with the database with Connection Interface.
3. Create Statement objects for Queries.
4. Execute the statements which may or may not return ResultSet.
5. Manipulate the ResultSet.
6. Close the Statements and Connection objects.

2/47
05/24/08 07:03:47

The following code will illustrate how to write the JDBC program.

package com.visualbuilder;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBCExample1 {

public static void main(String[] args) {


try {
/** Loading the ODBC- Bridge driver*/
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
/** Getting Connection*/
Connection con = DriverManager.getConnection(jdbc:odbc:MyDsn);
/** Creating Statement*/
Statement stmt = con.createStatement();
/** Creating simple table*/
stmt.execute(select * from employee);
/** Closing the Connection*/
con.close();
} catch (Exception e) {
e.printStackTrace();
}

3/47
05/24/08 07:03:47

Connection Interface

A Connection is the session between your java program and database. Whenever you do anything with database you have
to have a connection object. There are many ways we can establish the connection.

The connection object is obtained by the DriverManager.getConnectyion method by supplying the Database location and
authentication credentials.

The following are the ways to obtain a Connection object of the database:-

1. DriverManager.getConnection(String URL)

2. DriveManager.getConnection(String URL,String Username, String Password)

3. DriverManager.getConnection (String URL, java.util.Properties props)

4. Driver.connect(String URL, java.util.Properties props)

The coming example will cover all the ways for Connection.

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.util.Properties;

import org.gjt.mm.mysql.Driver;

public class JDBCConnectionExample {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

4/47
05/24/08 07:03:47

/** Getting Connection Type 2*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Type 3*/

/*Properties props = new Properties ();

props.put(user,root);

props.put(password,root);

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,props);*/

/** Type -4 */

Properties props = new Properties ();

props.put(user,root);

props.put(password,root);

Driver driver= new Driver();

Connection con = driver.connect(jdbc:mysql://localhost:3306/test,props);

System.out.println(Connection Established);

con.close();

} catch (Exception e) {

e.printStackTrace();

Output:-

Connection Established

5/47
05/24/08 07:03:47

The Data Model For the Examples

The following are the tables we use for all the examples in this tutorial.

VisualBuilder Table

Col=Id Col=Name Col= Description

Type =Int Type=varchar Type=CLOB


1 Sun Java null
2 Visual Builder null
3 Eclipse null
4 IBM null
5 Jakarta null
SQL Query:-

1. Create table visualbuilder ( Id int, name varchar(30), Description Clob);

2. Insert into visualbuilder (id, name) values(1,'Sun Java');

3. Insert into visualbuilder (id, name) values(2,'Visual Builder');

4. Insert into visualbuilder (id, name) values(3,'Eclipse');

5. Insert into visualbuilder (id, name) values(4,'IBM');

6. Insert into visualbuilder (id, name) values(5,'Jakarta');

Employee Table

Col= Id Col=Ename Col= DeptId

Type=Int Type= varchar Type= Int


1 Adam 1
2 Susan 2
3 Adran 3
4 Hardy 3
5 Tim 2
6 Michael 1
SQL Query:-

6/47
05/24/08 07:03:47

1. Create table employee ( id int, ename varchar(30), deptId);

2. Insert into employee (id, ename, deptid) values(1,'Adam',1);

3. Insert into employee (id, ename, deptid) values(2,'Susan',2);

4. Insert into employee (id, ename, deptid) values(3,'Adran',3);

5. Insert into employee (id, ename, deptid) values(4,'Hardy',3);

6. Insert into employee (id, ename, deptid) values(5,'Tim',2);

7. Insert into employee (id, ename, deptid) values(6,'Michael',3);

Department Table

Col= id Col= Dname

Type= int Type= varchar


1. Sales
2 Account
3 Marketing

SQL Query:-

1. Create table department ( id int, dname varchar(30));

2. Insert into department (id, dname) values(1,'Sales');

3. Insert into department (id, dname) values(2,'Account');

4. Insert into department (id, dname) values(3,'Marketing');

7/47
05/24/08 07:03:47

Basic CRUD functionality using Statements

In the first example we have seen how to execute the statement in JDBC. We will now discuss the CRUD(Create,
Retrieve, Update and Delete) functionality with JDBC.

The below example with tell how to implement CRUD operations using Statement interface.

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

public class StatementExample {

public static void main(String[] args) {

try {

/** Loading the ODBC- Bridge driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

Statement stmt = con.createStatement();

/** Creating simple table*/

stmt.executeUpdate(Create Table visualbuilder(id int(4) NOT NULL,name varchar(45)));

8/47
05/24/08 07:03:47

System.out.println(Table Created);

/** inserting Rows */

int i=stmt.executeUpdate( insert into visualbuilder(id,name)values(1,'Sun java'));

System.out.println(i + Recored(s) inserted);

/** Updating */

i= stmt.executeUpdate( update visualbuilder set name='visual builder');

System.out.println(i + Recored(s) Updated);

/** Deleting */

i= stmt.executeUpdate( delete from visualbuilder);

System.out.println(i + Recored(s) Deleted);

/** Closing the Connection*/

con.close();

} catch (Exception e) {

e.printStackTrace();

Output:-

Table Created

1 Recored(s) inserted

1 Recored(s) Updated

9/47
05/24/08 07:03:47

1 Recored(s) Deleted

10/47
05/24/08 07:03:47
Handling Data with Result Sets

There are many occurrences when the Java application needs to manipulate data in the database. Data can be retrieved by
using SELECT queries against the database. Java has provided a class ResultSet which is used to store the complete
dataset coming to a java program and then we can retrieve the data as per our requirement from the ResultSet class using
its methods.

The default behaviour of ResultSet objects are as follows:-

1. You can only retrieve data using appropriate getXXX() method.

2. You cannot go back in the ResultSet.means all are forward only resultsets.

The next example will demonstrate the use of ResultSet

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class BasicResultSetExample {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

11/47
05/24/08 07:03:47

Statement stmt = con.createStatement();

ResultSet rs=stmt.executeQuery(select * from visualbuilder);

while(rs.next()) {

System.out.print(Id is + rs.getInt(id));

System.out.println( Name is + rs.getString(name));

/** Closing the Connection*/

stmt.close();

con.close();

} catch (Exception e) {

e.printStackTrace();

Output:-

Id is 1 Name is Sun java

Id is 2 Name is Visual Builder

Id is 3 Name is Eclipse

Id is 4 Name is IBM

Id is 5 Name is Jakarta

12/47
05/24/08 07:03:47

Using PreparedStatements

The PreparedStatement interface inherits from Statement and differs from it in two ways:

1. The instances of PreparedStatement are already compiled so it is faster than the normal statements.

2. The parameters in the PreparedStatements are denoted by “?” and set at the runtime and we don’t have to convert any
datatypes in the process. We just have to call the appropriate set method example setString() etc.

Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. The three methods execute,
executeQuery, and executeUpdate are modified so that they take no argument.

The following example will demonstrate the use of the prepared statements in the java applications.

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

public class PreparedStatementExample {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

PreparedStatement pst = con.prepareStatement(insert into visualbuilder(id,name)values(?,?));

13/47
05/24/08 07:03:47

pst.setInt(1,1);

pst.setString(2,VisualBuilder);

int i= pst.executeUpdate();

System.out.println(i + Record(s) Inserted);

/** Closing the Connection*/

pst.close();

con.close();

} catch (Exception e) {

e.printStackTrace();

Output:-

1 Recored(s) inserted

14/47
05/24/08 07:03:47

Scrollable and Updateable ResultSets

In the last section, we have seen the ResultSet moving only in forward direction. In this section, we learn some advance
features of ResultSets. If some properties are set while creating the ResultSet then we can randomly fetch the data and
even update it witout any update queries.

The next example demonstrates the advance features of the ResultSet.

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class UpdateableAndScrollableRS {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

/** Getting ResultSet*/

ResultSet rs=stmt.executeQuery(select * from visualbuilder);

15/47
05/24/08 07:03:47

while(rs.next()) {

System.out.print(Id is + rs.getInt(id));

System.out.println( Name is +rs.getString(name));

rs.absolute(1);

rs.updateString(2,Visual Builder);

rs.updateRow();

rs.beforeFirst();

System.out.println(After Updation);

while(rs.next()) {

System.out.print(Id is + rs.getInt(id));

System.out.println( Name is +rs.getString(name));

/** Closing the Connection*/

stmt.close();

con.close();

} catch (Exception e) {

e.printStackTrace();

Output:-

Id is 1 Name is Sun java

Id is 2 Name is Visual Builder

Id is 3 Name is Eclipse

16/47
05/24/08 07:03:47

Id is 4 Name is IBM

Id is 5 Name is Jakarta

After Updation

Id is 1 Name is Visual Builder

Id is 2 Name is Visual Builder

Id is 3 Name is Eclipse

Id is 4 Name is IBM

Id is 5 Name is Jakarta

17/47
05/24/08 07:03:47

Adding, Updating and Deleting Rows using ResultSets.

The next section will tell you how to enter the data without any insert query and with the help of ResultSet class.

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class UpdateableAndScrollableRS {

public static void main(String[] args) {

try {

/** Loading the ODBC- Bridge driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

/** Getting ResultSet*/

ResultSet rs=stmt.executeQuery(select * from visualbuilder);

while(rs.next()) {

System.out.print(Id is + rs.getInt(id));

System.out.println( Name is + rs.getString(name));

18/47
05/24/08 07:03:47

rs.moveToInsertRow();

rs.updateInt(1,3);

rs.updateString(2,ResultSet Example);

rs.insertRow();

rs.beforeFirst();

System.out.println(After Adding The record);

while(rs.next()) {

System.out.print(Id is + rs.getInt(id));

System.out.println( Name is + rs.getString(name));

rs.last();

rs.deleteRow();

rs.updateRow();

rs.beforeFirst();

System.out.println(After Deleting The record);

while(rs.next()) {

System.out.print(Id is + rs.getInt(id));

System.out.println( Name is + rs.getString(name));

/** Closing the Connection*/

stmt.close();

con.close();

}catch (Exception e) {

e.printStackTrace();

19/47
05/24/08 07:03:47

Output:-

Id is 1 Name is Visual Builder

Id is 2 Name is VisualBuilder

After Adding The record

Id is 1 Name is Visual Builder

Id is 2 Name is VisualBuilder

Id is 3 Name is ResultSet Example

After Deleting The record

Id is 1 Name is Visual Builder

Id is 2 Name is VisualBuilder

20/47
05/24/08 07:03:47

Using Joins in JDBC Quries.

Sometimes user has to fetch the data from the different tables at the same time and on the basis of some conditions. Let us
consider there is an employee and Dept table. Employee table has the DeptId as the field but in case we want the name of
department then we have to fetch the employee information from the employee table and Dept name is taken out from the
dept table on the basis of dept id stored in the Employee table. For joins the two tables should be having some relations.

package com.visualbuilder;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JoinExample {

public static void main(String[] args) {


try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
/** Getting Connection*/
Connection con = DriverManager.getConnection
System.out.println(Connection estalished);
/** Creating Statement*/
Statement stmt = con.createStatement();
/** Creating simple table*/
ResultSetrs=stmt.executeQuery(select emp.ename,dept.dname from emp, dept
where dept.deptno =emp.deptno and emp.ename like 'A%');
while(rs.next())
{
System.out.print(Name of the employee is rs.getString(ename));
System.out.println( Dept name is rs.getString(dname));
}
/** Closing the Connection*/
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();

}
}

Output:-

Connection estalished

Name of the employee is Adam Dept name is Sales

21/47
05/24/08 07:03:47

Name of the employee is Adran Dept name is Marketing

22/47
05/24/08 07:03:47

Calling procedures with Callable Statement

Sometimes the it is not possible to retrieve the whole manipulated data with a single query from database. So many
queries clubbed together to form a single block. This block is known as procedures in database. So if you want to call
these blocks from your java programs so you need to use a special statement i.e Callable Statement. The below example
will demonstrate the parameter passing, calling mechanism and also getting the results from the Database procedures.

Suppose, there is a procedure Test for the adding the two numbers. Here is code for the procedure :-

TG DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`Test` $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `Test`(IN num1 INT, IN num2 INT ,OUT param1 INT)

BEGIN

set param1 := num1 + num2;

END $$ DELIMITER ;

The following code will call the procedure “Test”.

package com.visualbuilder;

import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Types;

public class CallableStatementExample {

public static void main(String[] args) {

try {

23/47
05/24/08 07:03:47

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

CallableStatement call = con.prepareCall(call test.Test(?,?,?));

call.setInt(1,2);

call.setInt(2,2);

call.registerOutParameter(3,Types.INTEGER);

call.execute();

System.out.println(The addition is +call.getInt(3));

con.close();

} catch (Exception e) {

e.printStackTrace();

Output is:-

The addition is 4

24/47
05/24/08 07:03:47
Transaction Management Part-1

Transaction is a complete task which is a combination of the smaller tasks. For the major task to be completed, the smaller
tasks need to be successfully completed. If any one task fails then all the previous tasks are reverted to the original state.

For example if you are withdrawing money it consist getting money, reducing the balance from account and also printing
a slip. If anything gets failed then all the things should be converted to its previous state. In order to achieve this type of
functionality where all the queries should be completed otherwise the task should be rolled back is acheieve by three
methods rollback(), commit() and setAutoCommit().

By default the connection commits all the changes once it is done with the single query. This can be stopped by calling
setAutoCommit(false) on connection object. Now for every transaction user has to explicitly call commit() method only
the changes get reflected otherwise changes wont be shown in the database. Rollback() method gets called for
withdrawing all the changes done by the queries in the database.

Note:- The program will not change any data as the commit() is called after rollback().

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

public class BasicTransactionExample {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

25/47
05/24/08 07:03:47

con.setAutoCommit(false);

Statement stmt= con.createStatement();

stmt.execute(delete from visualbuilder);

//Commits the transaction

System.out.println(Commit called );

con.rollback();

con.commit();

stmt.close();

con.close();

} catch (Exception e) {

e.printStackTrace();

Output:-

Commit called

26/47
05/24/08 07:03:47

Transaction Management Part-2

There are some situations when you have to only rollback() to some specific statement and not all statements in a
transaction. This can be achieved by introducing some labels to the statements in the transactions. These labels are
known as savepoints. The JDBC 3.0 API adds the method Connection.setSavepoint, which sets a savepoint within the
current transaction. The Connection.rollback method has been overloaded to take a savepoint argument.

The following example will demonstrate how do we use savepoints to handle the transactions more effectively.

Note:- The program will not change any data as the commit() is called after rollback().

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Savepoint;

import java.sql.Statement;

public class SavepointExample {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);

/** Creating Statement*/

con.setAutoCommit(false);

Statement stmt= con.createStatement();

27/47
05/24/08 07:03:47

stmt.execute(insert into visualbuilder (id,name)values(10,'test'));

// set savepoint

Savepoint savepoint1 = con.setSavepoint(SAVEPOINT_1);

stmt.execute(delete from visualbuilder);

System.out.println(rollback to savepoint called );

con.rollback(savepoint1);

con.commit();

con.close();

} catch (Exception e){

e.printStackTrace();

Output:-

rollback to savepoint called.

28/47
05/24/08 07:03:47

Connection pooling And Data Sources

A DataSource object represents a particular DBMS or some other data source, such as a file. If a company uses more than
one data source, it will deploy a separate DataSource object for each of them. In a native SQL environment the most of
the response time is used in creating and managing the connections in the database. So the architects has introduced the
connection pooling mechanism in which a pool of active connection is created at the startup of server or application and
then all java programs will borrow the connection as and when required. The freeing or connections will be taken care by
the pool itself so if user will not close the connection objects then it is done implicitly.

The below example will call the datasource in the weblogic server.

package com.visualbuilder;
import java.sql.Connection;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DataSourceExample {


public static void main(String[] args) {
Context ctx = null;
try {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
weblogic.jndi.WLInitialContextFactory);
ht.put(Context.PROVIDER_URL, t3://localhost:7001);
ctx = new InitialContext(ht);
DataSource ds = (DataSource)ctx.lookup(DataSourcePool);
Connection con = ds.getConnection();
System.out.println(Connection Established);
con.close();
}catch(Exception exp)
{
exp.printStackTrace();
}
}
}

Output:-

Connection Established

29/47
05/24/08 07:03:47

Batch Updates Using Statements

The Statement object can also be associated with more than one command at a time. These chunks of commands are
known as batch of statements. Commands are added to the list with the Statement method addBatch and the method
executeBatch submits stmt's list of commands to the underlying DBMS for execution. The execution of a batch may
throw BatchUpdateException if something goes worng with the execution. All the statements only return the simple count
and not any resultsets. In other words we can say the select statements are not allowed in batch statements. A Statement
object's list of commands can be emptied by calling the method clearBatch on it. The following example will execute the
batch of select statements.

package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchProcessingExample {

/**
* @param args
*/
public static void main(String[] args) {
try {
/** Loading the ODBC- Bridge driver*/
Class.forName(com.mysql.jdbc.Driver);
/** Getting Connection*/
Connection con =DriverManager.getConnection(jdbc:mysql://localhost:3306/test,root,root);
/**Creating Statement*/
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch(INSERT INTO visualbuilder VALUES(11,'visual'));
stmt.addBatch(INSERT INTO visualbuilder VALUES(12,'Builder'));
stmt.addBatch(INSERT INTO visualbuilder VALUES(13,'RAD'));
stmt.addBatch(INSERT INTO visualbuilder VALUES(14,'Eclipse'));
stmt.addBatch(INSERT INTO visualbuilder VALUES(15,'NetBeans'));
int [] updateCounts= stmt.executeBatch();
con.commit();
con.setAutoCommit(true);
System.out.println(Batch Successful);
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:-

Batch Successful

Note :- JDBC drivers are not required to support batch updates, so a particular driver might not implement the methods
addBatch, clearBatch, and executeBatch. Normally a programmer knows whether a driver that he/she is working with
supports batch updates, but if an application wants to check, it can call the DatabaseMetaData method

30/47
05/24/08 07:03:47

supportsBatchUpdates to find out.

31/47
05/24/08 07:03:47

Handling Batch/SQL Errors and Warnings

In the JDBC programs there are majorly two types of errors exit one is SQLException and BatchException. The
SQLException throws by the program if anything goes wrong with the database interaction like the connection not
established or some query syntax is not correct. The BatchException only occurs if something goes wrong in the batch
processing of the statements. Also we can retrieve the database warning in our program.

The program below illustrates how to deal with database warnings and SQLExceptions

package com.visualbuilder;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class ExceptionAndWarningExample {

public static void main(String[] args) {

try {

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:odbc:MyDsn,root,tiger);

System.out.println(Connection estalished);

/** Creating Statement*/

Statement stmt = con.createStatement();

ResultSet rs=stmt.executeQuery(select from emp);

stmt.close();

con.close();

32/47
05/24/08 07:03:47

}catch (ClassNotFoundException exp){

exp.printStackTrace();

}catch (SQLException exp) {

while (exp != null) {

System.out.println(Message: + exp.getMessage ());

System.out.println(SQLState: + exp.getSQLState ());

System.out.println(ErrorCode: + exp.getErrorCode ());

exp = exp.getNextException();

Output:-

Connection estalished

Message: [Oracle][ODBC][Ora]ORA-00936: missing expression

SQLState: S1000

ErrorCode: 936

The same way warnings can be handled as shown below :-

SQLWarning warn = stmt.getWarnings();

if (warn != null) {

System.out.println(n---Warning---n);

while (warn != null) {

33/47
05/24/08 07:03:47

System.out.println(Message: + warn.getMessage());

System.out.println(SQLState: + warn.getSQLState());

System.out.print(Vendor error code: );

System.out.println(warn.getErrorCode());

System.out.println();

warn = warn.getNextWarning();

34/47
05/24/08 07:03:47

Handling Blob and CLOB data using JDBC


The following example with demonstrate how to handle the large datasets in the queries. BLOB (Binary Large Objects )
and CLOB(Character large objects) are special datatypes and can hold the large chunks of data in form of objects or
text. Blob and Clob objects persist the data of the objects into the database as a stream or as a Java array

package com.visualbuilder;

import java.io.BufferedReader;

import java.io.FileReader;

import java.sql.Clob;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import javax.sql.rowset.serial.SerialClob;

public class BlobExample {

public static void main(String[] args) {

try {

/** Loading the driver*/

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

/** Getting Connection*/

Connection con = DriverManager.getConnection(jdbc:odbc:MyDsn,scott,tiger);

System.out.println(Connection established);

/** Creating Statement*/

PreparedStatement pst = con.prepareStatement(insert into visualbuilder(id,name,description)values(?,?,?));

pst.setInt(1,5);

35/47
05/24/08 07:03:47

pst.setString(2,VisualBuilder);

// Create a big CLOB value...

StringBuffer buffer = new StringBuffer(500000);

while (buffer.length() < 500000) {

buffer.append(This is the ClobExample);

String clobValue = buffer.toString();

pst.setString(3, clobValue);

int i= pst.executeUpdate();

System.out.println(Record Inserted);

pst.close();

con.close();

} catch (Exception e) {

e.printStackTrace();

Output is:-

Connection established

Record Inserted

36/47
05/24/08 07:03:47
Basics for Rowsets and JdbcRowSet Example

A RowSet object is a java bean component and extends the ResultSet interface Thus, it has a set of JavaBeans properties
and follows the JavaBeans event model. A RowSet object's properties allow it to establish its own database connection
and to execute its own query in order to fill itself with data

Types of Rowset

The RowSet is majorly classified into two types as per their properties:-

1. Connected Rowset.:- The connected rowset as the name suggests in connected to the database connection object like the
resultset. The JDBCRowSet is the example of the connected RowSet.

2. Disconnected RowSet:- The disconnected RowSet only connects to the database whenever required and after finishing
the interaction they close the database connection. So if the connection pool is minimally used in this case.

There are following ways to create the JDBCRowSet:-

37/47
05/24/08 07:03:47

1. Passing the ResultSet:- In this approach the data is populated in the object and then you can retrieve the data by using
the getter methods as we did in case of the ResultSet. Exmple:-

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(“select * from employee”);

JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);

2. Creating the default object:- This approach is useful if you want to set the data sources dynamically. In this approach
the Database URL, username and password is explicitly set in the RowSetObject.Exmple:-

JdbcRowSet jdbcRs = new JdbcRowSetImpl();

jdbcRs.setUsername(user);

jdbcRs.setPassword(password);

jdbcRs.setUrl(jdbc:mySubprotocol:mySubname);

jdbcRs.setCommand(select * from EMP );

jdbcRs.execute();

The following example will illustrate the basic operation using the JDBCRowSet interface.

package com.visualbuilder;

import java.sql.SQLException;

import javax.sql.rowset.JdbcRowSet;

import com.sun.rowset.JdbcRowSetImpl;

public class JDBCRowSetExample {

public static void main(String[] args) throws SQLException{

JdbcRowSet jdbcRs = new JdbcRowSetImpl();

38/47
05/24/08 07:03:47

jdbcRs.setUsername(scott);

jdbcRs.setPassword(tiger);

jdbcRs.setUrl(jdbc:odbc:MyDsn);

jdbcRs.setCommand(select * from employee);

jdbcRs.execute();

while(jdbcRs.next()) {

System.out.println(jdbcRs.getString(ename));

Ouput:-

Adam

Susan

Adran

Hardy

Tim

Michael

39/47
05/24/08 07:03:47

CachedRowSet

The CachedRowSet interface defines the basic capabilities available to all disconnected RowSet objects. The
cachedRowSet actually caches the data in its own location rather than getting data for all the operations and after
updations it will write back the updated data in the database. It also resolve the conflicts occurs during any update to data
in the database In the cachedRowSets the Key columns are set to identify the rows uniquely in the cache.

So it is advisable it should be same as primary key column defined in the database.

Note:- A disconnected RowSet object must call the method acceptChanges() in order to save its changes to the data
source.

package com.visualbuilder;

import javax.sql.rowset.CachedRowSet;

import com.sun.rowset.CachedRowSetImpl;

public class CachedRowSetExample {


public static void main(String[] args) throws Exception {

Class.forName(org.postgresql.Driver);
CachedRowSet cachedRs = new CachedRowSetImpl();
cachedRs.setUsername(user);
cachedRs.setPassword(pass);
cachedRs.setUrl(jdbc:postgresql://localhost:5432/postgres);
cachedRs.setCommand(select * from dept);
cachedRs.setPageSize(4);
cachedRs.execute();
System.out.println(The Deptartment Retrieved from the Database);
while (cachedRs.nextPage()) {
while (cachedRs.next()) {
System.out.println(cachedRs.getString(dname));
}
}
}

Output is:-

The Deptartment Retrieved from the Database

Sales

Account

Marketing

40/47
05/24/08 07:03:47

41/47
05/24/08 07:03:47

JoinRowSet
The JoinRowSet is used to hold the data coming from two or more tables. It can be achieved by using the join in sql.
The JoinRowSet has equivalent of an SQL JOIN without having to connect to a data source In order to get the joined
data one column in both tables should be common. The common column is known as the match column. The match
column is set by calling the addRowSet() method for each RowSet object with the column index and the RowSet objects
which you want to join.

The following code will illustrate the use of the JoinRowSet.

package com.visualbuilder;

import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.JoinRowSet;

import com.sun.rowset.CachedRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;

public class JoinRowSetExample {


public static void main(String[] args) throws Exception {
Class.forName(org.postgresql.Driver);
CachedRowSet employee = new CachedRowSetImpl();
employee.setUsername(postgres);
employee.setPassword(pass);
employee.setUrl(jdbc:postgresql://localhost:5432/postgres);
employee.setCommand(select id,ename,deptid from emp);
employee.execute();
CachedRowSet dept = new CachedRowSetImpl();
dept.setUsername(postgres);
dept.setPassword(pass);
dept.setUrl(jdbc:postgresql://localhost:5432/postgres);
dept.setCommand(select dept_id,dname from dept);
dept.execute();
JoinRowSet joinset=new JoinRowSetImpl();
joinset.addRowSet(employee,3);
joinset.addRowSet(dept,1);
while (joinset.next()){
System.out.println(Employee is +joinset.getString(ename));
System.out.println(Department is +joinset.getString(dname));
}
}
}

Ouput:-

Employee is Adam

Department is Sales

42/47
05/24/08 07:03:47

Employee is Susan

Department is Account

Employee is Adran

Department is Marketing

Employee is Hardy

Department is Marketing

Employee is Tim

Department is Account

Employee is Michael

Department is Sales

43/47
05/24/08 07:03:47

FilterRowSet
A FilteredRowSet object contains only the filtered rows from the database. The filter criteria is set in the RowSet object
and the RowSet only get the filtered data from the database to the object. The filters can ebe created by implemeting
Predicate interface. The following example will demonstrate the filter object creationg and how to apply the filters in
the RowSet object.

package com.visualbuilder;

import java.sql.SQLException;

import javax.sql.RowSet;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.Predicate;

import com.sun.rowset.FilteredRowSetImpl;

class Filter1 implements Predicate {


private String colName;

public Filter1(String colName) {


this.colName = colName;
}

public boolean evaluate(RowSet rs) {


try {
CachedRowSet crs = (CachedRowSet) rs;
String object = crs.getString(colName);
if (object != null
&& (object.charAt(0) == 'A' || object.charAt(0) == 'a')) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}

public boolean evaluate(Object arg0, int arg1) throws SQLException {

return false;
}

public boolean evaluate(Object arg0, String arg1) throws SQLException {

return false;
}

44/47
05/24/08 07:03:47

public class FillterRowSetExample {


public static void main(String[] args) throws Exception {
Class.forName(org.postgresql.Driver);
FilteredRowSet frs = new FilteredRowSetImpl();
frs.setUsername(postgres);
frs.setPassword(pass);
frs.setUrl(jdbc:postgresql://localhost:5432/postgres);
frs.setCommand(select id,ename,deptid from employee);
frs.setFilter(new Filter1(ename));
frs.execute();
while (frs.next()) {
System.out.println(Employee is + frs.getString(id));
System.out.println(Department is + frs.getString(ename));
}
}
}

Output:-

Employee is Adam

Department is Sales

Employee is Adran

Department is Marketing

45/47
05/24/08 07:03:47

WebRowSet

Today in the WWW the XML is well established mechanism for data exchange. The webRowSet has all the functionality
of the CachedRowSet as well as it is capable of reading and writing data directly from the xml file. The xml file which is
used should have properties, metadata and actual data for the rowset object. The following example will illustrate the
creation of xml data and how to use it in the RowSet object.

package com.visualbuilder;

import javax.sql.rowset.WebRowSet;

import com.sun.rowset.WebRowSetImpl;

public class WebRowSetExample {


public static void main(String[] args) throws Exception{
Class.forName(org.postgresql.Driver);
WebRowSet webRs = new WebRowSetImpl();
webRs.setUsername(postgres);
webRs.setPassword(pass);
webRs.setUrl(jdbc:postgresql://localhost:5432/postgres);
webRs.setCommand(select * from dept);
webRs.execute();
java.io.FileWriter reader = new java.io.FileWriter(c:/dept.xml);
webRs.writeXml(reader);
}
}

Output:-

Note:- The example will create a file named dept.xml under the C Drive. The sample file dept.xml can be downloaded with
the java source.

46/47
05/24/08 07:03:47

Next steps
We hope you found this tutorial useful and enjoyed reading it.

Do give us your feedback.

There are several other JSP, Java tutorials on the site be sure to check them out.

Date entered : 26th Jul 2007


Rating :No Rating
Submitted by : visualbuilder

Copyright Visualbuilder.com 1999-2006


Document created date: 24 May 2008

47/47

Você também pode gostar