CHAPTER 3 Oracle Data Base Connectivity
CHAPTER 3 Oracle Data Base Connectivity
CHAPTER 3 Oracle Data Base Connectivity
Java Database Connectivity (JDBC) is an application programming interface (API) for Java that
allows Java applications to access and manipulate data stored in relational databases. JDBC provides a
standard way for Java applications to connect to different databases, regardless of the specific
database vendor or product.
There are many reasons why you might want to use JDBC in your Java applications:
Portability: JDBC allows you to write Java applications that can access data stored in a variety of
databases, without having to write separate code for each database.
Ease of use: JDBC provides a simple and easy-to-use API for accessing and manipulating
database data.
Performance: JDBC is a high-performance API that can efficiently access and manipulate data in
large databases.
Pluggability: JDBC is a pluggable API, which means that you can use different JDBC drivers to
connect to different databases.
JDBC works by providing a set of classes and interfaces that represent the different components
of a database connection, such as the database connection, the SQL statement, and the result set.
These classes and interfaces allow Java applications to interact with the database in a standard way,
regardless of the specific database vendor or product.
Driver manager: The driver manager is responsible for loading the appropriate JDBC driver for
the database that you want to connect to.
Connection: A connection represents a connection to a database. You use a connection to execute
SQL statements against the database.
Statement: A statement represents an SQL statement that you want to execute against the
database.
ResultSet: A result set contains the results of an SQL query.
How do I use JDBC?
1. Load the JDBC driver for the database that you want to connect to.
2. Establish a connection to the database.
3. Create a statement object.
4. Execute an SQL statement using the statement object.
5. Process the results of the SQL statement.
6. Close the connection to the database.
To connect java application with the oracle database, we need to follow 5 following steps. In this
example, we are using Oracle 10g as the database. So we need to know following information for the
oracle database:
Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port
number and XE is the Oracle service name. You may get all these information from the tnsnames.ora
file.
Username: The default username for the oracle database is system.
Password: It is the password given by the user at the time of installing the oracle database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.
create table emp(id number(10),name varchar2(40),age number(3));
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
download this example
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
The data source facility provides a complete replacement for the previous JDBC DriverManager
facility. You can use both facilities in the same application, but it is recommended that you transition
your application to data sources.
JNDI enables an application to use logical names in accessing these services, removing vendor-
specific syntax from application code. JNDI has the functionality to associate a logical name with a
particular source for a desired service.
All Oracle JDBC data sources are JNDI-referenceable. The developer is not required to use this
functionality, but accessing databases through JNDI logical names makes the code more portable.
eatures and Properties of Data Sources
By using the data source functionality with JNDI, you do not need to register the vendor-specific
JDBC driver class name and you can use logical names for URLs and other properties. This ensures
that the code for opening database connections is portable to other environments.
A JDBC data source is an instance of a class that implements the standard javax.sql.DataSource
interface:
To use other values, you can set properties using appropriate setter methods. For alternative user
names and passwords, you can also use the getConnection method that takes these parameters as
input. This would take priority over the property settings.
3.4 DATA SOURCES FOR DATA BASE CONNECTIVITY
Note:
• This table omits properties that supported the deprecated connection cache based on
OracleConnectionCache.
• Because Native XA performs better than Java XA, use Native XA whenever possible.
Use the setConnectionProperties method to set the properties of the connection and the
setConnectionCacheProperties method to set the properties of the connection cache.
If you are using the server-side internal driver, that is, the driverType property is set to kprb, then
any other property settings are ignored.
If you are using the JDBC Thin or OCI driver, then note the following:
• A URL setting can include settings for user and password, as in the following example, in
which case this takes precedence over individual user and password property settings:
Copy jdbc:oracle:thin:HR/hr@localhost:5221:orcl
• Settings for user and password are required, either directly through the URL setting or
through the getConnection call. The user and password settings in a getConnection call take
precedence over any property settings.
• If the url property is set, then any tnsEntry, driverType, portNumber, networkProtocol,
serverName, and databaseName property settings are ignored.
• If the tnsEntry property is set, which presumes the url property is not set, then any
databaseName, serverName, portNumber, and networkProtocol settings are ignored.
• If you are using an OCI driver, which presumes the driverType property is set to oci, and the
networkProtocol is set to ipc, then any other property settings are ignored.
Also, note that getConnectionCacheName() will return the name of the cache only if the
ConnectionCacheName property of the data source is set after caching is enabled on the data source.
Create an OracleDataSource instance, initialize its connection properties as appropriate, and get a
connection instance, as in the following example:
Program:
OracleDataSource ods = new OracleDataSource();
ods.setDriverType("oci");
ods.setServerName("localhost");
ods.setNetworkProtocol("tcp");
ods.setDatabaseName(<database_name>);
ods.setPortNumber(5221);
ods.setUser("HR");
ods.setPassword("hr");
Once you have initialized the connection properties of the OracleDataSource instance ods, as
shown in the preceding example, you can register this data source instance with JNDI, as in the
following example:
Copy
Context ctx = new InitialContext();
ctx.bind("jdbc/sampledb", ods);
Calling the JNDI InitialContext() constructor creates a Java object that references the initial JNDI
naming context. System properties, which are not shown, instruct JNDI which service provider to use.
The ctx.bind call binds the OracleDataSource instance to a logical JNDI name. This means that
anytime after the ctx.bind call, you can use the logical name jdbc/sampledb in opening a connection to
the database described by the properties of the OracleDataSource instance ods. The logical name
jdbc/sampledb is logically bound to this database.
The JNDI namespace has a hierarchy similar to that of a file system. In this example, the JNDI
name specifies the subcontext jdbc under the root naming context and specifies the logical name
sampledb within the jdbc subcontext.
The Context interface and InitialContext class are in the standard javax.naming package.
Note:The JDBC 2.0 Specification requires that all JDBC data sources be registered in the jdbc
naming subcontext of a JNDI namespace or in a child subcontext of the jdbc subcontext.
Open a Connection
To perform a lookup and open a connection to the database logically bound to the JNDI name, use
the logical JNDI name. Doing this requires casting the lookup result, which is otherwise a Java
Object, to OracleDataSource and then using its getConnection method to open the connection.
Here is an example:
Set a password file on the server-side or on the remote database, using the orapwd password
utility. You can add a password file for user SYS as follows:
In UNIX
orapwd file=$ORACLE_HOME/dbs/orapwORACLE_SID entries=200
Enter password: password
In Microsoft Windows
orapwd file=%ORACLE_HOME%\database\PWDORACLE_SID.ora entries=200
Enter password: password
In this case, file is the name of the password file, password is the password for user SYS. It can be
altered using the ALTER USER statement in SQL Plus. You should set entries to a value higher than
the number of entries you expect.
Enable remote login as SYSDBA. This step grants SYSDBA and SYSOPER system privileges to
individual users and lets them connect as themselves.
Stop the database, and add the following line to initservice_name.ora, in UNIX, or init.ora, in
Microsoft Windows:
Copy
remote_login_passwordfile=exclusive
The initservice_name.ora file is located at ORACLE_HOME/dbs/ and also at
ORACLE_HOME/admin/db_name/pfile/. Ensure that you keep the two files synchronized.
Change the password for the SYS user. This is an optional step.
PASSWORD sys
Changing password for sys
New password: password
Retype new password: password
Verify whether SYS has the SYSDBA privilege.
SQL> select * from v$pwfile_users;
USERNAME SYSDB SYSOP
---------------------- --------- ---------
SYS TRUE TRUE
Restart the remote database.
Copy
/** Example of bequeath connection **/
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;
1. What is JDBC?
2. What are the benefits of using JDBC?
3. What are the core components of JDBC?
4. How do you load a JDBC driver?
5. How do you establish a connection to a database using JDBC?
6. How do you create a statement object?
7. How do you execute an SQL statement using JDBC?
8. How do you process the results of an SQL query?
9. How do you close a connection to a database using JDBC?
10. What are some common JDBC exceptions?
11. Advanced JDBC Concepts
23. What are some of the best practices for using JDBC?
24. What are some common mistakes that people make when using JDBC?
25. What are some resources that you can use to learn more about JDBC?
TERMINAL QUESTIONS
1. What is the JDBC driver manager and its role in establishing database connections?
2. Describe the different types of JDBC statements (Statement, PreparedStatement,
CallableStatement) and their usage scenarios.
3. Explain the concept of result sets in JDBC and how to process them effectively.
4. How do you establish a connection to an Oracle database using JDBC?
5. What is the difference between a Type-1 and Type-4 JDBC driver?
6. How do you handle exceptions and errors in JDBC applications?
7. What are some best practices for writing secure JDBC code?
8. How do you optimize JDBC performance for large-scale applications?
9. Intermediate JDBC Questions
18. How do you implement custom JDBC drivers for Oracle databases?
19. Describe how to use JDBC to interact with Oracle object-relational features, such as stored
procedures, functions, and packages.
20. Explain how to integrate JDBC with Oracle enterprise features, such as Oracle Data Guard
and Oracle Real Application Clusters.
21. Discuss the role of JDBC in Oracle Cloud Infrastructure (OCI) cloud-based database services.
22. How do you secure JDBC applications against common SQL injection attacks?
23. Discuss the performance implications of different JDBC connection pooling strategies.
24. What are some emerging trends and future directions in JDBC development?