0% found this document useful (0 votes)
39 views

Advanced Programming Chapter 1 Java Database ConnectivityJDBC

The document discusses JDBC and how to connect Java applications to databases. It describes what JDBC is, the different types of JDBC drivers, and the basic steps to establish a database connection from Java using JDBC including loading the driver, creating a connection URL, and getting a connection object.

Uploaded by

birhanu131313
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Advanced Programming Chapter 1 Java Database ConnectivityJDBC

The document discusses JDBC and how to connect Java applications to databases. It describes what JDBC is, the different types of JDBC drivers, and the basic steps to establish a database connection from Java using JDBC including loading the driver, creating a connection URL, and getting a connection object.

Uploaded by

birhanu131313
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Chapter 1: Java Database Connectivity (JDBC)

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:

• Making a connection to a database


• Creating SQL or MySQL statements
• Executing SQL or MySQL queries in the database
• Viewing & modifying the resulting records

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:

• Core JAVA Programming


• SQL or MySQL Database

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:

• JDBC API: This provides the application-to-JDBC Manager connection.


• JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

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 Types:

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.

Type 2: JDBC-Native API:


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the
database. These drivers typically provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.

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.

Type 3: JDBC-Net pure Java:


In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard
network sockets to communicate with a middleware application server. The socket information is then
translated by the middleware application server into the call format required by the DBMS, and forwarded
to the database server.

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.

Type 4: 100% pure Java:


A Type 4 driver is a pure Java-based driver that communicates directly with vendor's database through
socket connection. This is the highest performance driver available for the database and is usually provided
by the vendor itself.

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.

JDBC Database Connections

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.

Java Database Connectivity (JDBC) with MySQL


Before we continue, let’s create a simple database schema and Java project that we will use.

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:

public class Register_student_profile{


public static void main(String[] args) {

// TODO Auto-generated method stub

}
}

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;

Step 2: Loading the database Driver

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

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Database name ",


"database user name", "database password");

In this example the database connection code looks like

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student Profile


Registration DB ", "root", "root");

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{

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student Profile


Registration DB ", "root", "root");
System.out.println("Connected successfully");
} catch (SQLEXception e) {
System.out.println(e.getMessage());

}
}

The following is the output

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.

Let us create a statement like this

Statement stmt = conn.createStatement();

Here, conn is our database connection reference.

Step 5: Issue commands using the connection.

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.

Example of inserting one row in the student_profile table

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)";

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;

public class Register_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());
}

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)";

int inserted = stmt.executeUpdate(sql);

if (inserted == 1) {
System.out.println("Inserted successfully");
} else {
System.out.println("Insertion failed");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}

How to fetch data from database?

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());
}
}
}

How to update data stored in database?

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";

String str="update student_profile set First_Name=?, Entry_Year=? where Student_Id=?";


ps=conn.prepareStatement(str);
ps.setString(1, fname);
ps.setInt(2, entryyear);
ps.setString(3, studid);
int updated=ps.executeUpdate();
if(updated>0)
{
System.out.println("updated successfully");
} else {
System.out.println("Failed to update");
}
conn.close();

} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

15

You might also like