Database and JDBC
Database and JDBC
A database is an organized collection of logically related data. The databases use Database
Management Systems (DBMS) software to provide mechanism for storing, organizing, retrieving
and modifying data for many users. The DBMS also provides programming interface (API) to
enable application program to use database services. In this activity you will use JDBC and
MySql or SQL Server as your DBMS to:-
Asked to read on Java Database Connectivity (JDBC) and to perform the following task: - (asked
to use MySql or SQL Server as your DBMS)
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.
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
executables, such as − • Java Applications
• Java Applets
• Java Servlets
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database
independent code.
Pre-Requisite
Before moving further, you need to have a good understanding of the following two subjects −
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 −
Common JDBC Components
• 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.
• 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.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your data
sources.
The new features in these packages include changes in the following areas −
• Annotations.
1) In diagram, indicate the relationship between Java code, JDBC API and Database Driver
(of your choice)
The relationship between Java code, JDBC API, and the database driver is as follows:
The Java code communicates with the database using the JDBC API. The JDBC API
provides the necessary methods for connecting to the database, executing SQL
statements, and processing results. The database driver, which is specific to the database
management system (DBMS) being used, implements the JDBC API. The driver acts as a
bridge between the Java code and the database, converting the Java calls into the specific
database commands.
2) Itemize requirements necessary to use JDBC and any DBMS (Install all packages and
drivers).
3) Understand the steps involved when using JDBC to connect to the DBMS and retrieve
data from database into command line, or inserting/update data into tables (i.e packages,
classes, methods , object etc) i.e
Loading driver
Establishing connection
Creating a statement
Executing statements
Processing ResultSet and closing your connection
The steps involved in using JDBC to connect to a DBMS and retrieve data are as follows:
import java.sql.*;
class Test { public
static void
main(String[] args)
{ try {
//Loading driver
Class.forName("oracle .jdb
c.driver.OracleDri ver");
}
con.close(); //closing connection
} catch (Exception e)
{ e.printStacktrace();
In this step we will create statement object using createStatement() method. It is used to execute
the sql queries and defined in Connection class. Syntax of the method is given below. Syntax
Statement s=con.createStatement();
After creating statement, now execute using executeQuery() method of Statement interface.
This method is used to execute SQL statements. Syntax of the method is given below. Syntax
In this example, we are executing a sql query to select all the records from the user table and
stored into resultset that further is used to display the records.
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
Closing the connection
This is final step which includes closing all the connection that we opened in our previous steps.
After executing SQL statement you need to close the connection and release the session.
The close() method of Connection interface is used to close the connection. Syntax
con.close();
Exception handling is important when using JDBC to ensure that errors are properly
handled and prevent the application from crashing. You can use a try-catch block to catch
exceptions thrown by the JDBC API and handle them appropriately.
5) Write a SQL query for
To create database called StudentData
name VARCHAR(255),
age INT
);
name VARCHAR(255),
duration INT
);
Use java code to Insert/ update in your code / retrieve on command line data into/
from database tables.
Insertion or updation
String sql = "INSERT INTO Student (name, age) VALUES (?, ?)";
statement.setInt(2, 25);
Prepared statements can be used to insert, select, update, and delete data in the database. They
allow you to precompile an SQL statement and then execute it multiple times with different
values. For example, to insert data into the Student table using a prepared statement:
String sql = "INSERT INTO Student (name, age) VALUES (?, ?)";
statement.setInt(2, 30);
To perform batch insert, update, and dynamically insert multiple rows into the database
using JDBC, you can use the addBatch() and executeBatch() methods of the Statement or
PreparedStatement objects. For example, to perform a batch insert into the Student table:
String sql = "INSERT INTO Student (name, age) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, "Nasibu Omary");
statement.setInt(2, 25);
statement.addBatch();
statement.setString(1, "Nasibu Omary");
statement.setInt(2, 30);
statement.addBatch();
int[] rowsInserted = statement.executeBatch();
Similarly, for batch update and dynamically inserting multiple rows, you can use the
addBatch() and executeBatch() methods.