database connectivity
database connectivity
As a developer, you can use JDBC to interact with a database from within a Java program.
JDBC acts as a bridge from your code to the database, as shown in Figure 1.
IDG
Figure 1. JDBC connects Java programs to databases.
JDBC vs ODBC
Before JDBC, developers used Open Database Connectivity (ODBC), a language-agnostic standard
approach to accessing a relational database management system, or RDBMS. In some ways, JDBC
takes its inspiration from ODBC.
The difference is that JDBC is Java-specific, offering a programming-level interface that handles the
mechanics of Java applications communicating with a database.
JDBC’s architecture
1. The JDBC API supports communication between the Java application and the JDBC manager.
2. The JDBC driver supports communication between the JDBC manager and the database driver.
The JDBC API and JDBC driver have been refined extensively over the years, resulting in a feature-
rich, performant, and reliable library.
JDBC is the common API that your application code interacts with. Beneath that is the
Figure 2. JDBC’s architecture consists of the JDBC API and JDBC drivers.
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Disadvantage:
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver. It is fully written in Java language.
Disadvantage:
What is API
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.
There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
o Import sql package
o Loa driver class
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
JDBC imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
Each of these imports provides access to a class that facilitates the standard Java database
connection:
SQLException handles SQL errors between the Java application and the database.
ResultSet and Statement model the data result sets and SQL statements.
The forName() method of Class class is used to register the driver class. This method is used to dynamically loa
the driver class.
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's
Jar in the classpath, and then JDBC driver manager can detect and load the driver automatically.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the database.
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create statement. The object of statement
responsible to execute queries with the database.
Syntax:
2. Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED STATEMENT
at run time.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL statements
such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and set the values in the ? holders,
setXXX() of a prepared statement is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name
3. Callable Statement are stored procedures which are a group of statements that we compile
in the database for some task, they are beneficial when we are dealing with multiple tables with
complex scenario & rather than sending multiple queries to the database, we can
send the required data to the stored procedure & lower the logic executed in the database
server itself. The Callable Statement interface provided by JDBC API helps in executing stored
procedures.
Syntax: To prepare a CallableStatement
The executeQuery() method of Statement interface is used to execute queries to the database. This method return
the object of ResultSet that can be used to get all the records of a table.
1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/bank where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and bank is the database name. We may use any database, in such
case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
import java.sql.*;
import java.util.*;
String un = sc.nextLine();
String pw = sc.nextLine();
Class.forName("com.mysql.jdbc.Driver");
/*Statement st = con.createStatement();
while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getFloat(3));
}*/
pspt.setString(1, un);
pspt.setString(2, pw);
if(rs1.next()) {
else {
System.out.println("wrong details");
con.close();