Chapter- 7 Database
Chapter- 7 Database
JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX.
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Applications of JDBC
Java can be used to write different types of executables, such as :
Java Applications
Java Applets
Java Servlets
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases.
JDBC Architecture
Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application :
Common JDBC Components
The JDBC API provides the following interfaces and classes :
Driver − This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.
Common JDBC Components
Connection − This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
Statement − You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in addition to
executing stored procedures.
ResultSet − These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
SQLException − This class handles any errors that occur in a database application.
Creating JDBC Application
There are following six steps involved in building a JDBC application:
Import the packages − Requires that you include the packages containing the JDBC classes
needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create
Connection object, which represents a physical connection with the database.
Execute a query − Requires using an object of type Statement for building and submitting an
SQL statement to the database.
Extract data from result set − Requires that you use the appropriate ResultSet.getXXX()
method to retrieve the data from the result set.
Clean up the environment − Requires explicitly closing all database resources versus relying
on the JVM's garbage collection.
Creating JDBC Application
Import JDBC Packages
The Import statements tell the Java compiler where to find the classes you reference in
your code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete
data in SQL tables, add the following imports to your source code −
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
Creating JDBC Application
Register JDBC Driver
Registering the driver is the process by which the Oracle driver's class file is loaded into
the memory, so it can be utilized as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one
of two ways.
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName()
method, to dynamically load the driver's class file into memory, which automatically
registers it. This method is preferable because it allows you to make the driver
registration configurable and portable.
Creating JDBC Application
Register JDBC Driver
The following example uses Class.forName( ) to register the Oracle driver :
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
System.out.println(con);
System.out.println("database is conneected");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ConnectMYSQL.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ConnectMYSQL.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Creating JDBC Application
Register JDBC Driver
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as
the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1); }
Creating JDBC Application
Database URL Formulation
After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods :
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Creating JDBC Application
Following table lists down the popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only the
remaining part as per your database setup.
Creating JDBC Application
Create Connection Object
We have listed down three forms of DriverManager.getConnection() method to create a
connection object.
Using a Database URL with a username and password
The most commonly used form of getConnection() requires you to pass a database
URL, a username, and a password
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName
value for the database portion of the URL.
Creating JDBC Application
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your
Oracle listener is configured to listen on port 1521, and your database name is EMP,
then complete database URL would be : jdbc:oracle:thin:@amrood:1521:EMP
DELIMITER ;
Creating JDBC Application
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all the three.
Parameter Description