Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
The following steps are required to write any JDBC specific programs in java.
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;
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)
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;
try {
Class.forName(com.mysql.jdbc.Driver);
4/47
05/24/08 07:03:47
props.put(user,root);
props.put(password,root);
/** Type -4 */
props.put(user,root);
props.put(password,root);
System.out.println(Connection Established);
con.close();
} catch (Exception e) {
e.printStackTrace();
Output:-
Connection Established
5/47
05/24/08 07:03:47
The following are the tables we use for all the examples in this tutorial.
VisualBuilder Table
Employee Table
6/47
05/24/08 07:03:47
Department Table
SQL Query:-
7/47
05/24/08 07:03:47
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;
try {
Class.forName(com.mysql.jdbc.Driver);
8/47
05/24/08 07:03:47
System.out.println(Table Created);
/** Updating */
/** Deleting */
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.
2. You cannot go back in the ResultSet.means all are forward only resultsets.
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName(com.mysql.jdbc.Driver);
11/47
05/24/08 07:03:47
while(rs.next()) {
System.out.print(Id is + rs.getInt(id));
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
Output:-
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;
try {
Class.forName(com.mysql.jdbc.Driver);
13/47
05/24/08 07:03:47
pst.setInt(1,1);
pst.setString(2,VisualBuilder);
int i= pst.executeUpdate();
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
Output:-
1 Recored(s) inserted
14/47
05/24/08 07:03:47
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.
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName(com.mysql.jdbc.Driver);
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
15/47
05/24/08 07:03:47
while(rs.next()) {
System.out.print(Id is + rs.getInt(id));
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));
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
Output:-
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 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta
17/47
05/24/08 07:03:47
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;
try {
Class.forName(com.mysql.jdbc.Driver);
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
while(rs.next()) {
System.out.print(Id is + rs.getInt(id));
18/47
05/24/08 07:03:47
rs.moveToInsertRow();
rs.updateInt(1,3);
rs.updateString(2,ResultSet Example);
rs.insertRow();
rs.beforeFirst();
while(rs.next()) {
System.out.print(Id is + rs.getInt(id));
rs.last();
rs.deleteRow();
rs.updateRow();
rs.beforeFirst();
while(rs.next()) {
System.out.print(Id is + rs.getInt(id));
stmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
19/47
05/24/08 07:03:47
Output:-
Id is 2 Name is VisualBuilder
Id is 2 Name is VisualBuilder
Id is 2 Name is VisualBuilder
20/47
05/24/08 07:03:47
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;
}
}
Output:-
Connection estalished
21/47
05/24/08 07:03:47
22/47
05/24/08 07:03:47
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 $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `Test`(IN num1 INT, IN num2 INT ,OUT param1 INT)
BEGIN
END $$ DELIMITER ;
package com.visualbuilder;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;
try {
23/47
05/24/08 07:03:47
Class.forName(com.mysql.jdbc.Driver);
call.setInt(1,2);
call.setInt(2,2);
call.registerOutParameter(3,Types.INTEGER);
call.execute();
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;
try {
Class.forName(com.mysql.jdbc.Driver);
25/47
05/24/08 07:03:47
con.setAutoCommit(false);
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
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;
try {
Class.forName(com.mysql.jdbc.Driver);
con.setAutoCommit(false);
27/47
05/24/08 07:03:47
// set savepoint
con.rollback(savepoint1);
con.commit();
con.close();
e.printStackTrace();
Output:-
28/47
05/24/08 07:03:47
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;
Output:-
Connection Established
29/47
05/24/08 07:03:47
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
31/47
05/24/08 07:03:47
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;
try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
System.out.println(Connection estalished);
stmt.close();
con.close();
32/47
05/24/08 07:03:47
exp.printStackTrace();
exp = exp.getNextException();
Output:-
Connection estalished
SQLState: S1000
ErrorCode: 936
if (warn != null) {
System.out.println(n---Warning---n);
33/47
05/24/08 07:03:47
System.out.println(Message: + warn.getMessage());
System.out.println(SQLState: + warn.getSQLState());
System.out.println(warn.getErrorCode());
System.out.println();
warn = warn.getNextWarning();
34/47
05/24/08 07:03:47
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;
try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
System.out.println(Connection established);
pst.setInt(1,5);
35/47
05/24/08 07:03:47
pst.setString(2,VisualBuilder);
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.
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:-
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:-
jdbcRs.setUsername(user);
jdbcRs.setPassword(password);
jdbcRs.setUrl(jdbc:mySubprotocol:mySubname);
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;
38/47
05/24/08 07:03:47
jdbcRs.setUsername(scott);
jdbcRs.setPassword(tiger);
jdbcRs.setUrl(jdbc:odbc:MyDsn);
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.
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;
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:-
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.
package com.visualbuilder;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.JoinRowSet;
import com.sun.rowset.CachedRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;
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;
return false;
}
return false;
}
44/47
05/24/08 07:03:47
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;
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.
There are several other JSP, Java tutorials on the site be sure to check them out.
47/47