0% found this document useful (0 votes)
26 views13 pages

Database and JDBC

The document provides information on using Java Database Connectivity (JDBC) to connect to and interact with databases. It discusses: 1) The architecture of JDBC including its API, driver manager, and database-specific drivers. 2) Common JDBC components like Connection, Statement, and ResultSet interfaces. 3) Steps to use JDBC which include loading the driver, establishing a connection, creating statements, executing queries, processing result sets, and closing the connection. 4) An example code snippet demonstrating these steps.

Uploaded by

Hassan Yassin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views13 pages

Database and JDBC

The document provides information on using Java Database Connectivity (JDBC) to connect to and interact with databases. It discusses: 1) The architecture of JDBC including its API, driver manager, and database-specific drivers. 2) Common JDBC components like Connection, Statement, and ResultSet interfaces. 3) Steps to use JDBC which include loading the driver, establishing a connection, creating statements, executing queries, processing result sets, and closing the connection. 4) An example code snippet demonstrating these steps.

Uploaded by

Hassan Yassin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

THE UNIVERSITY OF DODOMA

COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COURSE NAME: BSC. COMPUTER NETWORK AND INFORMATION SECURITY


ENGINEERING.

COURSE CODE: CP 215

COURSE NAME: OBJECT-ORIENTED PROGRAMMING

INSTRUCTOR: Mr. Balongo

Reading and Practical Activity on Database and JDBC


Deadline: Friday 23:59 5th February, 2023

REGISTRATION NUMBER: T21-03-01972


Introduction

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

i. To understand the concepts of databases, database management systems and SQL.


ii. To learn how to load a driver, connect to a database, execute statements, and process
result sets using JDBC.
iii. To use prepared statements to execute precompiled SQL statements.
iv. To explore database metadata using the DatabaseMetaData and ResultSetMetaData
interfaces
ANSWERS TO TASKS

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.

• 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
executables, such as − • Java Applications

• Java Applets

• Java Servlets

• Java ServerPages (JSPs)

• Enterprise JavaBeans (EJBs).

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 −

• Core JAVA Programming

• SQL or MySQL Database

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 −
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 sub protocol. The first driver that recognizes a certain sub-protocol under
JDBC will be used to establish a database Connection.

• 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 −

• Automatic database driver loading.

• Exception handling improvements.

• Enhanced BLOB/CLOB functionality.

• Connection and statement interface enhancements.

• National character set support.

• SQL ROWID access.

• SQL 2003 XML data type support.

• 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).

To use JDBC with a DBMS, you will need the following:

 Java Development Kit (JDK)

 A database management system (DBMS) such as MySQL or SQL Server

 A JDBC driver specific to the DBMS being used

 A Java Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA

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:

i. Load the database driver by using the Class.forName() method and


passing the driver class name as a parameter.
ii. Establish a connection to the database by using the
DriverManager.getConnection() method and passing the connection URL,
username, and password as parameters.
iii. Create a statement by using the Connection.createStatement() method.
iv. Execute the SQL statements by using the Statement.executeQuery()
method for SELECT statements or the Statement.executeUpdate() method
for INSERT, UPDATE, and DELETE statements.
v. Process the result set by using the ResultSet object returned from the
executeQuery() method.
vi. Close the connection by using the Connection.close() method.
Syntax for above scenario

getConnection(String url) getConnection(String url, String


username,
String password) getConnection(String url, Properties info)
This is a sample example to establish connection with Oracle
Drive
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username","password");

import java.sql.*;
class Test { public
static void
main(String[] args)
{ try {
//Loading driver
Class.forName("oracle .jdb
c.driver.OracleDri ver");

//creating connection Connection con =


DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "username",
"password");

Statement s = con.createStatement(); //creating statement

ResultSet rs = s.executeQuery("select * from Student"); //executing statement

while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2));

}
con.close(); //closing connection
} catch (Exception e)
{ e.printStacktrace();

Create SQL Statement

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

public Statement createStatement() throws SQLException

Example to create a SQL statement

Statement s=con.createStatement();

Execute SQL Statement

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

public ResultSet executeQuery(String query) throws SQLException

Example to execute a SQL statement

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.

ResultSet rs=s.executeQuery("select * from user"); while(rs.next())


{

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

public void close() throws SQLException

Example of closing a connection

con.close();

4) Make sure your handle exception

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

CREATE TABLE Student (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255),

age INT

);

 Create table called Student and Course

CREATE TABLE Course (

id INT AUTO_INCREMENT PRIMARY KEY,

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 (?, ?)";

PreparedStatement statement = connection.prepareStatement(sql);

statement.setString(1, "Nasibu Omary");

statement.setInt(2, 25);

int rowsInserted = statement.executeUpdate();

To retrieve data from the Student table on the command line

SELECT * FROM Student;

6) Use preparedStatement to insert, select, update and delete operation

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 (?, ?)";

PreparedStatement statement = connection.prepareStatement(sql);

statement.setString(1, "Jane Doe");

statement.setInt(2, 30);

int rowsInserted = statement.executeUpdate();


7) Use JDBC to perform batch insert, batch update and dynamically insert multiple rows
into your databases.

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.

You might also like