Advanced Programming Chapter 1 Java Database ConnectivityJDBC
Advanced Programming Chapter 1 Java Database ConnectivityJDBC
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API (Application Program Interface)
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 commonly associated with database usage:
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executable java technologies,
such as:
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
All of these different executables are able to use a JDBC driver to access a database and take advantage of
the stored data.
Pre-Requisite:
Before progressing, you need to have good understanding on the following two subjects:
1
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in general
JDBC Architecture consists of two layers:
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.
Following is the architectural diagram, which shows the location of the driver manager with respect to the
JDBC drivers and the Java application:
2
Common JDBC Components:
The JDBC API provides the following interfaces and classes:
• DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication subprotocol.
• Driver: This interface handles the communications with the database server.
• 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: Use objects created from this interface to hold data retrieved from a database after you
execute SQL query using Statement objects. It acts as temporary table that allow you to move
through its data.
• SQLException: This class handles any errors that occur in a database application.
The java.sql package that ships with JDK contains various classes with their behaviors defined and their
actual implementations are done in third-party drivers. Third party vendors implement the
java.sql.Driver interface in their database driver.
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.
For example, using JDBC drivers enable you to open database connections and to interact with it by sending
SQL or database commands then receiving results with Java.
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms
in which Java operates. JDBC driver divided into four categories, Types 1, 2, 3, and 4, which are explained
below:
3
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using
ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but
now this type of driver is recommended only for experimental use or when no other alternative is available.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
If we change the Database we have to change the native API as it is specific to a database and they are
mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates
ODBC's overhead.
4
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver
can actually provide access to multiple databases.
5
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding
the nuances will prove helpful.
This kind of driver is extremely flexible; you don't need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
Oracle thin driver and MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of
their network protocols, database vendors usually supply type 4 drivers.
6
Which Driver should be used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred
driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level driver and is typically used for development and
testing purposes only.
After you've installed the appropriate driver, it's time to establish a database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these simple four
steps:
• Import JDBC Packages: Add import statements to your Java program to import required classes in
your Java code.
• Register JDBC Driver: This step causes the JVM to load the desired driver implementation into
memory so it can fulfill your JDBC requests.
• Database URL Formulation: This is to create a properly formatted address that points to the
database to which you wish to connect.
• Create Connection Object: Finally, code a call to the DriverManager object's getConnection( )
method to establish actual database connection.
Create a database with the name Student Profile Registration DB(use user name as root and
password root and create a table with the name student_profile(Student_Id(pk), First_Name,
Second_Name, Date_Of_Birth, Entry_Year).
7
Let’s now create a new java project called Student Profile Registration System using Eclipse IDE
The following steps shows you how to connect your java project(application) to the selected database,
in this case Student Profile Registration System java project to Student Profile Registration DB
Step 1: Download and import the MYSQL JDBC driver (mysql-connector-j-8.3.0) class into your
java application.
Now create a new java class with the name Register_student_profile under the project Student Profile
Registration System and you will get the following class syntax:
}
}
Now let’s import the required JDBC components to your java application (Register_student_profile
class) before the class name
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
Before connecting to the database, you will need to load the driver and register it to use the driver in
your java application. Driver registration is done once in your application.
Class.forName(): Here we load the driver;s class file into memory at the run-time like this
Class.forName("com.mysql.cj..jdbc.Driver");
8
Step 3: Establish a connection using the JDBC library
After loading the driver, we now make a connection to the database like this
Driver manager class has a method called getConnection() which returns connection and expects three
arguments, i.e. Database url, database user name and database password to establish connection to
MySQL database.
When MySQL is used, we use jdbc:mysql driver. Localhost is the IP address where the database is
located, 3306 is the port number for MySQL database.
You need to catch errors that might occur by use of try-catch statements or throws exception
statement.
This is the content of our java class at this point. Please run the code to ensure you successfully connect
to the database.
9
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class Register_student_profile{
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
try{
}
}
Connected successfully
If you see any error, ensure your MySQL server is running and started. Then also ensure your added
MySQL JDBC library in your project.
10
Step 4: Create a statement
After a successful connection has been established, you can now interact with the database. Statement
and PreparedStatement interfaces provide methods for sending queries and receiving data from your
database.
Once a statement has been created, you can now execute it (SQL Query). This is the most important
part. There are queries for inserting, updating, and selecting(viewing) data from databases, and you are
familiar with basic SQL statements like INSERT, UPDATE, DELETE, and SELECT.
The executeQuery() method of Statement interface is used to issue commands for getting data from the
database. This method returns an object of ResultSet that is used to get all records of a table based on
the SQL query statement.
The executeUpdate(sql) method is used to issue commands for inserting, updating and deleting.
int m = stmt.executeUpdate(sql);
if (m == 1) {
System.out.println("Inserted successfully");
} else {
System.out.println("Insertion failed");
11
Step 6: Close the connection
So after completing our work, we close our connection. We use the close() method of the Connection
interface to close the connection. Objects of ResultSet and Statements are closed automatically when
we close the connection.
Example:
conn.close();
Finally, the above Java Database Connection Implementation code is merged and shown as below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName(driverName);
}
catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
try {
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt = conn.createStatement();
12
String sql = "insert into student_profile (Student_Id, First_Name,Second_Name,
Date_Of_Birth,Entry_Year) VALUES ('TER/1221/2014','Biruk', 'Solomon', '1993', 2015)";
if (inserted == 1) {
System.out.println("Inserted successfully");
} else {
System.out.println("Insertion failed");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
Create new java class called View_student_profile and write the following codes The codes show you
how to fetch all the records of student_profile table
import java.sql.*;
class View_student_profile{
public static void main(String[] args) {
String driverName="com.mysql.cj.jdbc.Driver";
String dbUrl="jdbc:mysql://localhost:3306/student profile registration db";
String dbusername="root";
String dbpassword="root";
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName(driverName);
}
catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
13
try {
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from student_profile");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+" "+rs.getInt(5));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
Create new java class called Update_student_profile and write the following codes The codes show you
how to update record based on a given condition
import java.sql.*;
class Update_student_profile{
public static void main(String[] args) {
String driverName="com.mysql.cj.jdbc.Driver";
String dbUrl="jdbc:mysql://localhost:3306/student profile registration db";
String dbusername="root";
String dbpassword="root";
Connection conn=null;
PreparedStatement ps=null;
try{
Class.forName(driverName);
}
catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
14
try {
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
String fname="Abel";
int entryyear=2014;
String studid="TER/1221/2014";
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
15