Fundamental Steps in JDBC - Using Java Database Connectivity (JDBC) With Oracle - InformIT
Fundamental Steps in JDBC - Using Java Database Connectivity (JDBC) With Oracle - InformIT
Pearson
EVERYDAY DISCOUNT OFFER Buy 2 or more eligible tles and save 35%*—use code BUY2. Shop now.
Related Resources
Using Java Database Connec vity (JDBC) with Oracle Store Ar cles Blogs
By Bulusu Lakshman
Apr 5, 2002 Core Java, Volume II--
Advanced Features, 11th
Edi on
📄 Contents ⎙ Print + Share This < Back Page 2 of 7 Next >
By Cay S. Horstmann
Book $51.99
This is for making the JDBC API classes immediately available to the applica on program. The following
Learn More Buy
import statement should be included in the program irrespec ve of the JDBC driver being used:
import java.sql.*;
www.informit.com/articles/article.aspx?p=26251&seqNum=3 1/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
Addi onally, depending on the features being used, Oracle-supplied JDBC packages might need to be
imported. For example, the following packages might need to be imported while using the Oracle
extensions to JDBC such as using advanced data types such as BLOB, and so on.
import oracle.jdbc.driver.*;
import oracle.sql.*;
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
For the en re Java applica on, the JDBC driver is registered only once per each database that needs
to be accessed. This is true even when there are mul ple database connec ons to the same data
server.
Alterna vely, the forName() method of the java.lang.Class class can be used to load and
register the JDBC driver:
Class.forName("oracle.jdbc.driver.OracleDriver");
However, the forName() method is valid for only JDK-compliant Java Virtual Machines and implicitly
creates an instance of the Oracle driver, whereas the registerDriver() method does this explicitly.
Connec ng to a Database
Once the required packages have been imported and the Oracle JDBC driver has been loaded and
registered, a database connec on must be established. This is done by using the getConnection()
method of the DriverManager class. A call to this method creates an object instance of the
java.sql.Connection class. The getConnection() requires three input parameters, namely, a
connect string, a username, and a password. The connect string should specify the JDBC driver to be
yes and the database instance to connect to.
Three parameters, one each for the URL, username, and password.
Only one parameter for the database URL. In this case, the URL contains the username and
password.
We will discuss the methods of opening a connec on using the Oracle JDBC OCI and thin _drivers. This chapter is from the book
When using the OCI driver, the database can be specified using the TNSNAMES entry in the
tnsnames.ora file. For example, to connect to a database on a par cular host as user oratest and Oracle and Java Development
password oratest that has a TNSNAMES entry of oracle.world, use the following code:
Learn More Buy
www.informit.com/articles/article.aspx?p=26251&seqNum=3 2/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
Both the ":" and "@" are mandatory.
When using the JDBC thin driver, the TNSNAMES entry cannot be used to iden fy the database. There
are two ways of specifying the connect string in this case, namely,
Explicitly specifying the hostname, the TCP/IP port number, and the Oracle SID of the
database to connect to. This is for thin driver only.
For example, for the explicit method, use the following code to connect to a database on host
training where the TCP/IP listener is on port 1521, the SID for the database instance is Oracle, the
username and password are both oratest:
This method can also be used for the JDBC OCI driver. Just specify oci8 instead of thin in the above
keyword-value pair list.
Alterna vely, the SQL statement can be placed in a string and then this string passed to the
executeQuery() func on. This is shown below.
This chapter is from the book
String sql = "SELECT empno, ename, sal, deptno FROM emp ORDER BY ename";
Oracle and Java Development
ResultSet rset = sql_stmt.executeQuery(sql);
Statement and ResultSet objects open a corresponding cursor in the database for SELECT and other
DML statements.
www.informit.com/articles/article.aspx?p=26251&seqNum=3 3/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
The above statement executes the SELECT statement specified in between the double quotes and
stores the resul ng rows in an instance of the ResultSet object named rset.
Processing the Results of a Database Query That Returns Mul ple Rows
Once the query has been executed, there are two steps to be carried out:
The first step is done using the next() method of the ResultSet object. A call to next() is
executed in a loop to fetch the rows one row at a me, with each call to next() advancing the control
to the next available row. The next() method returns the Boolean value true while rows are s ll
available for fetching and returns false when all the rows have been fetched.
The second step is done by using the getXXX() methods of the JDBC rset object. Here getXXX()
corresponds to the getInt(), getString() etc with XXX being replaced by a Java datatype.
String str;
while (rset.next())
{
str = rset.getInt(1)+ " "+ rset.getString(2)+ "
"+rset.getFloat(3)+ " "rset.getInt(4)+ "\n";
}
byte buf[] = str.getBytes();
OutputStream fp = new FileOutputStream("query1.lst");
fp.write(buf);
fp.close();
The parameters for the getXXX() methods can be specified by posi on of the corresponding
columns as numbers 1, 2, and so on, or by directly specifying the column names enclosed in double
quotes, as getString("ename") and so on, or a combina on of both.
rset.close();
sql_stmt.close();
Closing the ResultSet and Statement objects frees the corresponding cursor in the database.
This chapter is from the book
Closing the Connec on
The last step is to close the database connec on opened in the beginning a er impor ng the packages
Oracle and Java Development
and loading the JDBC drivers. This is done by a call to the close() method of the Connec on class.
Learn More Buy
The following line of code does this:
conn.close();
www.informit.com/articles/article.aspx?p=26251&seqNum=3 4/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
Explicitly Close your Connec on
Closing the ResultSet and Statement objects does not close the connec on. The connec on
should be closed by explicitly invoking the close() method of the Connection class.
A complete example of the above procedures using a JDBC thin driver is given below. This program
queries the emp table and writes the output rows to an opera ng system file.
NO_DATA_FOUND excep on in PL/SQL is simulated in JDBC by using the return value of the next()
method of the ResultSet object. A value of false returned by the next() method iden fies a
NO_DATA_FOUND excep on.
Consider the following code (this uses the ResultSet object rset defined in the above sec ons):
if (rset.next())
// Process the row returned
else
System.out.println("The Employee with Empno "+ args[1] + This chapter is from the book
"does not exist");
Instead of the while loop used earlier, an if statement is used to determine whether the SELECT
Learn More Buy
statement returned a row or not.
Datatype Mappings
www.informit.com/articles/article.aspx?p=26251&seqNum=3 5/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
Corresponding to each SQL data type, there exist mappings to the corresponding JDBC Types, standard
Java types, and the Java types provided by Oracle extensions. These are required to be used in JDBC
programs that manipulate data and data structures based on these types.
There are four categories of Data types any of which can be mapped to the others. These are:
SQL Data types—These are Oracle SQL data types that exist in the database.
JDBC Typecodes—These are the data typecodes supported by JDBC as defined in the
java.sql.Types class or defined by Oracle in oracle.jdbc.driver.OracleTypes
class.
Java Types—These are the standard types defined in the Java language.
Oracle Extension Java Types—These are the Oracle extensions to the SQL data types and
are defined in the oracle.sql.* class. Mapping SQL data types to the oracle.sql.*
Java types enables storage and retrieval of SQL data without first conver ng into Java
format thus preven ng any loss of informa on.
Table 3.1 lists the default mappings exis ng between these four different types.
SQL Data JDBC Type codes Standard Java Types Oracle Extension Java _
types Types
www.informit.com/articles/article.aspx?p=26251&seqNum=3 6/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
Oracle Extensions
oracle.sql.BFILE_
Just as PL/SQL provides for an implicit or explicit RAISE statement for an excep on, Oracle JDBC
programs have a throw statement that is used to inform that JDBC calls throw the SQL excep ons.This
This chapter is from the book
is shown below.
throws SQLException
Learn More Buy
www.informit.com/articles/article.aspx?p=26251&seqNum=3 7/9
12/11/2019 Fundamental Steps in JDBC | Using Java Database Connectivity (JDBC) with Oracle | InformIT
And, like in PL/SQL, SQL excep ons in JDBC have to be handled explicitly. Similar to PL/SQL excep on
handling sec ons, Java provides a try..catch sec on that can handle all excep ons including SQL
excep ons. Handling an excep on can basically include retrieving the error code, error text, the SQL
state, and/or prin ng the error stack trace. The SQLException class provides methods for obtaining
all of this informa on in case of error condi ons.
getErrorCode()
This func on returns the five-digit ORA number of the error in case of excep ons occurring
in the JDBC driver as well as in the database.
getMessage()
This func on returns the error message text in case of excep ons occurring in the JDBC
driver. For excep ons occurring in the database, this func on returns the error message
text prefixed with the ORA number.
getSQLState()
This func on returns the five digit code indica ng the SQL state only for excep ons
occurring in the database.
We now show the QueryExample class of the earlier sec on with complete excep on handlers built
in it. The code is as follows:
+ Share This 🔖 Save To Your Account < Back Page 2 of 7 Next >
www.informit.com/articles/article.aspx?p=26251&seqNum=3 9/9