JAVA_UNIT_III
JAVA_UNIT_III
DATABASE
JAVA IN DATABASES
WHAT IS DATABASE?
EXPLAIN ABOUT JAVA DATABASE.
Java is a popular programming language that can be used to interact with databases. There are several
ways to connect Java applications to databases, including JDBC (Java Database Connectivity) and
frameworks like Hibernate and JPA (Java Persistence API).
JDBC is a standard Java API for connecting and executing SQL statements on a database.
Hibernate is an Object-Relational Mapping (ORM) framework that simplifies database interactions by
mapping Java objects to database tables.
JPA is a specification for managing relational data in Java applications. Developers can choose the most
suitable approach based on their project requirements and preferences.
Introduction
JDBC is a standard Java API for database-independent connectivity between the Java programming
language and a wide range of databases. This application program interface lets you encode the access
request statements, in Structured Query Language (SQL). They are then passed to the program that
manages the database. It mainly involves opening a connection, creating a SQL Database, executing SQL
queries, and then arriving at the output.
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete, and fetch data from the databases. It is similar to the Open Database
Connectivity (ODBC) provided by Microsoft.
For a better understanding of the working of JDBC, let’s dive deeper into the topic and understand the
architecture that lies behind Java Database Connectivity.
JDBC ARCHITECTURE
EXPLAIN IN DETAIL ABOUT 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.
Common JDBC Components
The JDBC API provides the following interfaces and classes −
1
1. DriverManager is used to manage a list of database drivers. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
2. Driver is an interface that handles the communications with the database server. It also abstracts the
details associated with working with Driver objects.
3. Connection is an interface that consists all the methods required to connect to a database. The
connection object represents communication context, i.e., all communication with the database is
through connection object only.
Steps to create JDBC Application
In order to create JDBC Application, we need to follow few steps. Let’s see what they are.
1. Import the packages: You need to include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
2. Register the JDBC driver: Here you have to initialize a driver so that you can open a communication
channel with the database.
3. Open a connection: Here, you can use the getConnection() method to create a Connection object, which
represents a physical connection with the database.
4. Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to the database.
5. Extract data from result set: Requires that you use the appropriate getXXX() method to retrieve the data
from the result set.
6. Clean up the environment: Requires explicitly closing all database resources versus relying on the
JVM’s garbage collection.
JDBC Driver Types
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server.
Essentially, a JDBC driver makes it possible to do three things:
1. Establish a connection with a data source.
2. Send queries and update statements to the data source.
3. Process the results.
For example, the use of JDBC drivers enables you to open a database connection to interact with it by
sending SQL or database commands.
There are 4 types of drivers, namely:
Type 1: JDBC-ODBC Bridge Diver
Type 2: JDBC-Native API
Type 3: JDBC-Net pure Java
Type 4: 100% Pure Java
Type 1: JDBC-ODBC Bridge Diver
In Type 1 driver, a JDBC bridge accesses
ODBC drivers installed on each client machine.
Further, ODBC configures 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.
2
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 are 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.
3
load the desired driver implementation into memory so that it can fulfill your JDBC requests. There are 2
approaches to register a driver.
The most common approach to register a driver is to use Java’s forName()method to dynamically load the
driver’s class file into memory, which automatically registers it. This method is preferable because it
allows you to make the driver registration configurable and portable. Refer the below code.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
The second approach you can use to register a driver is to use the static registerDriver()method.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
We should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one
provided by Microsoft.
3. Database URL Formulation: This is to create a properly formatted address that points to the database to
which you wish to connect. After you’ve loaded the driver, you can establish a connection using
the DriverManager.getConnection() method.
DriverManager.getConnection() methods are−
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your database.
A table lists down the popular JDBC driver names and database URL.
The Java application calls JDBC classes and interfaces to submit SQL statements and retrieve results.
The JDBC API is implemented through the JDBC driver. The JDBC Driver is a set of classes that
implement the JDBC interfaces to process JDBC calls and return result sets to a Java application. The
database (or data store) stores the data retrieved by the application using the JDBC Driver.
The main objects of the JDBC API include:
A DataSource object is used to establish connections. Although the Driver Manager can also be
used to establish a connection, connecting through a DataSource object is the preferred method.
A Connection object controls the connection to the database. An application can alter the behavior
of a connection by invoking the methods associated with this object. An application uses the
connection object to create statements.
Statement, PreparedStatement, and CallableStatement objects are used for executing SQL
statements. A PreparedStatement object is used when an application plans to reuse a statement
multiple times. The application prepares the SQL it plans to use. Once prepared, the application can
specify values for parameters in the prepared SQL statement. The statement can be executed multiple
times with different parameter values specified for each execution. A CallableStatement is used to
call stored procedures that return values. The Callable Statement has methods for retrieving the
return values of the stored procedure.
A ResultSet object contains the results of a query. A ResultSet is returned to an application when a
SQL query is executed by a statement object. The ResultSet object provides methods for iterating
through the results of the query.
DATABASE ACCESS
HOW TO ACCESS DATA IN JAVA.
To access a database in advanced Java, you typically use JDBC (Java Database Connectivity) API. Here
are the steps to access a database in advanced Java using JDBC:
1. Load the JDBC driver: First, you need to load the JDBC driver for the specific database you are
using. This can be done using the Class.forName() method.
2. Establish a connection: Use the DriverManager.getConnection() method to establish a connection to
the database by providing the database URL, username, and password.
3. Create a statement: Create a Statement or PreparedStatement object to execute SQL queries against
the database.
4. Execute SQL queries: Use the executeQuery() method to retrieve data from the database or
executeUpdate() method to perform insert, update, or delete operations.
5. Process the results: If you are executing a query, use methods like ResultSet.next() to iterate through
the results and extract data.
6. Close the connection: Finally, close the connection, statement, and result set to release resources.
Here's a simple example of accessing a MySQL database in Java using JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
5
import java.sql.Statement;
public class DatabaseAccessExample {
public static void main(String[] args) {
try {
// Load MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
// Create statement
Statement statement = connection.createStatement();
// Execute query
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");
// Process results
while(resultSet.next()) {
System.out.println(resultSet.getString("column_name"));
}
// Close resources
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} }}
Remember to replace "com.mysql.cj.jdbc.Driver", "jdbc:mysql://localhost:3306/mydatabase",
"username", "password", "SELECT * FROM mytable", and "column_name" with your actual database
configurations and SQL queries.
INTERACTING
HOW TO INTERACT WITH DATABASE
To interact with a database in Java, you can use JDBC (Java Database Connectivity) which is a standard
API for accessing databases. Here's a high-level overview of how we can do this in advanced Java:
1. First, we need to establish a connection to the database. we can do this by loading the appropriate
JDBC driver and creating a connection object with the database URL, username, and password. For
example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
// proceed with database operations using this connection
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
2. Once the connection is established, you can create and execute SQL queries to interact with the
database. For example, you can retrieve data from a table:
import java.sql.Connection;
import java.sql.DriverManager;
6
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseInteraction {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");
while (resultSet.next()) {
// process each row of the result set
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3. Remember to handle exceptions appropriately, close the connection, statement, and result set after you
are done with your database operations to avoid resource leaks.
DATABASE SEARCH
EXPLAIN ABOUT HOW TO SEARCH IN DATABASE.
To perform a database search in advanced Java programming, you can use JDBC (Java Database
Connectivity) API.
Import the database
Load and register drivers
Create a connection
Create a statement
Execute the query
Process the results
Close the connection
1. Establish a connection to the database using JDBC:
Connection conn = DriverManager.getConnection("jdbc:database_url", "username", "password");
2. Create a SQL query to search the database:
String sql = "SELECT * FROM table_name WHERE condition";
3. Create a PreparedStatement to execute the SQL query:
PreparedStatement pstmt = conn.prepareStatement(sql);
4. Execute the query and retrieve the results:
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// Process the results here
}
5. Close the ResultSet, PreparedStatement, and Connection:
rs.close();
pstmt.close();
conn.close();
Remember to handle exceptions such as SQLException appropriately in your code. This is a basic
outline, and depending on your specific requirements, you can customize the query and processing logic
accordingly.
For more advanced database operations in Java, you can consider using frameworks like Hibernate or
Spring JDBC templates. These frameworks provide higher-level abstractions and simplify database
interactions.
CREATING MULTIMEDIA DATABASE
HOW TO CREATE MUTIMEDIA DATABASE? EXPLAIN IT.
7
Multimedia databaseis the collection of interrelated multimedia data that includes text, graphics
(sketches, drawings), images, animations, video, audio etc and have vast amounts of multisource
multimedia data.
The framework that manages different types of multimedia data which can be stored, delivered and
utilized in different ways is known as multimedia database management system.
There are three classes of the multimedia database which includes static media, dynamic media and
dimensional media.
Content of Multimedia Database management system:
Media data – The actual data representing an object.
Media format data – Information such as sampling rate, resolution, encoding scheme etc. about the
format of the media data after it goes through the acquisition, processing and encoding phase.
Media keyword data – Keywords description relating to the generation of data. It is also known as
content descriptive data. Example: date, time and place of recording.
Media feature data – Content dependent data such as the distribution of colors, kinds of texture and
different shapes present in data.
Types of multimedia applications based on data management characteristic are :
Repository applications – A Large amount of multimedia data as well as meta-data(Media format
date, Media keyword data, Media feature data) that is stored for retrieval purpose, e.g., Repository of
satellite images, engineering drawings, radiology scanned pictures.
Presentation applications – They involve delivery of multimedia data subject to temporal
constraint. Optimal viewing or listening requires DBMS to deliver data at certain rate offering the
quality of service above a certain threshold. Here data is processed as it is delivered. Example:
Annotating of video and audio data, real-time editing analysis.
Collaborative work using multimedia information – It involves executing a complex task by
merging drawings, changing notifications. Example: Intelligent healthcare network.
There are still many challenges to multimedia databases, some of which are :
Modelling – Working in this area can improve database versus information retrieval techniques thus,
documents constitute a specialized area and deserve special consideration.
Design – The conceptual, logical and physical design of multimedia databases has not yet been
addressed fully as performance and tuning issues at each level are far more complex as they consist
of a variety of formats like JPEG, GIF, PNG, MPEG which is not easy to convert from one form to
another.
Storage – Storage of multimedia database on any standard disk presents the problem of
representation, compression, mapping to device hierarchies, archiving and buffering during input-
output operation. In DBMS, a ”BLOB”(Binary Large Object) facility allows untyped bitmaps to be
stored and retrieved.
Performance – For an application involving video playback or audio-video synchronization,
physical limitations dominate. The use of parallel processing may alleviate some problems but such
techniques are not yet fully developed. Apart from this multimedia database consume a lot of
processing time as well as bandwidth.
Queries and retrieval –For multimedia data like images, video, audio accessing data through query
opens up many issues like efficient query formulation, query execution and optimization which need
to be worked upon.
Areas where multimedia database is applied are :
Documents and record management: Industries and businesses that keep detailed records and
variety of documents. Example: Insurance claim record.
Knowledge dissemination: Multimedia database is a very effective tool for knowledge
dissemination in terms of providing several resources. Example: Electronic books.
Education and training: Computer-aided learning materials can be designed using multimedia
sources which are nowadays very popular sources of learning. Example: Digital libraries.
Marketing, advertising, retailing, entertainment and travel. Example: a virtual tour of cities.
Real-time control and monitoring: Coupled with active database technology, multimedia
presentation of information can be very effective means for monitoring and controlling complex
tasks Example: Manufacturing operation control.
Several issues must be addressed if multimedia data are to be stored in a database:
8
The database must support large objects, since multimedia data such as videos can occupy up to a
few gigabytes of storage. Many database systems do not support objects larger than a few gigabytes.
Larger objects could be split into smaller pieces and stored in the database. Alternatively, the
multimedia object may be stored in a file system, but the database may contain a pointer to the
object; the pointer would typically be a file name. The SQL/MED standard (MED stands for
Management of External Data) allows external data, such as files, to be treated as if they are part of
the database. With SQL/MED, the object would appear to be part of the database, but can be stored
externally.
The retrieval of some types of data, such as audio and video, has the requirement that data delivery
must proceed at a guaranteed steady rate. Such data are sometimes called isochronous data, or
continuous-media data. For example, if audio data are not supplied in time, there will be gaps in the
sound. If the data are supplied too fast, system buffers may overflow, resulting in loss of data.
Similarity-based retrieval is needed in many multimedia database applications. For example, in a
database that stores fingerprint images, a query fingerprint image is provided, and fingerprints in the
database that are similar to the query fingerprint must be retrieved. Index structures such as B+- trees
and R-trees cannot be used for this purpose; special index structures need to be created.
To create a multimedia database in advanced Java, you would typically follow these steps:
1. Define the database schema: Determine the structure of your multimedia database, including the
tables to store multimedia content such as images, videos, and audio files.
2. Set up a database: Use a database management system like MySQL or PostgreSQL to create the
database and tables according to the defined schema.
3. Develop a Java application: Create a Java application that connects to the database using JDBC (Java
Database Connectivity) to perform CRUD (Create, Read, Update, Delete) operations on multimedia
content.
4. Handle multimedia files: Use Java libraries like Java Image I/O for images, Java Media Framework
for videos, and Java Sound API for audio to handle multimedia files within your application.
5. Implement search functionality: Develop search functionalities to retrieve multimedia content based
on user queries. You can use SQL queries or full-text search techniques for efficient retrieval.
6. Add security features: Implement authentication and authorization mechanisms to secure access to
the multimedia database and ensure data privacy.
By following these steps, you can create a robust multimedia database in advanced Java that efficiently
stores and retrieves multimedia content.
DATABASE SUPPORT IN WEB APPLICATIONS
WHAT DATABASES ARE SUPPORTED IN WEB APPLICATIONS?
To provide database support in web applications using advanced Java, you can follow these steps:
1. Choose a database management system (DBMS) that is compatible with Java, such as MySQL,
PostgreSQL, Oracle, or SQL Server.
2. Use Java Database Connectivity (JDBC) to connect your Java application to the chosen DBMS. JDBC
is a Java API for connecting and executing SQL queries with a database.
3. Utilize Object-Relational Mapping (ORM) frameworks like Hibernate or JPA to map Java objects to
database tables and simplify data manipulation.
4. Implement proper database connection pooling to enhance performance and efficiency in handling
multiple user requests.
5. Secure your database by following best practices such as parameterized queries to prevent SQL
injection attacks.
6. Use transactions to ensure data integrity and consistency in your web application.
Java Web Application is used to create dynamic websites. Java provides support for web application
through Servlets and JSPs. We can create a website with static HTML pages but when we want
information to be dynamic, we need web application. The aim of this article is to provide basic details of
different components in Web Application and how can we use Servlet and JSP to create our first java
web application.
Java Web Application is used to create dynamic websites.
Java provides support for web application through Servlets and JSPs.
We can create a website with static HTML pages but when we want information to be dynamic, we need
web application.
9
Java Web Application The aim of this article is to provide basic details of different components in Web
Application and how can we use Servlet and JSP to create our first java web application.
1. Web Server and Client
2. HTML and HTTP
3. Understanding URL
4. Why we need Servlet and JSPs?
5. First Web Application with Servlet and JSP
6. Web Container
7. Web Application Directory Structure
8. Deployment Descriptor
Web Server and Client
Web Server is a software that can process the client request and send the response back to the client. For
example, Apache is one of the most widely used web servers. Web Server runs on some physical
machine and listens to client request on a specific port. A web client is a software that helps in
communicating with the server. Some of the most widely used web clients are Firefox, Google Chrome,
Safari, etc. When we request something from the server (through URL), the web client takes care of
creating a request and sending it to the server and then parsing the server response and present it to the
user.
HTML and HTTP
Web Server and Web Client are two separate softwares, so there should be some common language for
communication.
HTML is the common language between server and client and stands for HyperText Markup Language.
Web server and client needs a common communication protocol, HTTP (HyperText Transfer Protocol)
is the communication protocol between server and client. HTTP runs on top of TCP/IP communication
protocol.
Some of the important parts of the HTTP Request are:
HTTP Method - action to be performed, usually GET, POST, PUT etc.
URL - Page to access
Form Parameters - similar to arguments in a java method, for example user,password details from
login page.
By following these steps, you can effectively incorporate database support into your advanced Java web
applications.
Understanding URL
URL is the acronym of Universal Resource Locator and it’s used to locate the server and resource. Every
resource on the web has its own unique address.
The unique address of the server, most of the times it’s the hostname of the server that maps to unique IP
address.
Sometimes multiple hostnames point to same IP addresses and web server virtual host takes care of
sending a request to the particular server instance.
It can be static html, pdf, JSP, servlets, PHP etc. Web servers are good for static contents HTML pages
but they don’t know how to generate dynamic content or how to save data into databases, so we need
another tool that we can use to generate dynamic content.
There are several programming languages for dynamic content like PHP, Python, Ruby on Rails, Java
Servlets and JSPs.
Java Servlet and JSPs are server-side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.
POSSIBLE QUESTIONS
PART A (1 MARK)
10
2. Select the packages in which JDBC classes are defined?
a. jdbc and javax.jdbc c. rdb and javax.rdb
b. jdbc and java.jdbc.sql d. sql and javax.sql
3. Which of the following method is used to perform DML statements in JDBC?
a. executeResult() c. executeQuery()
b. executeUpdate() d. execute()
4. What information is typically required to establish a JDBC connection?
a. Database name and SQL query c. JDBC URL, username, and password
b. Database table structure d. JDBC driver class
5. Which file is used to specify the packaging cycle?
a. build.xml c. pom.xml
b. dependency.xml d. version.xml
6. Which environment variable is used to specify the path to maven?
a. Java_home c. Path
b. Maven_home d. Classpath
7. Servlet are used to program which component in a web application?
a. Client c. server
b. Tomcat d. applet
8. Which component can be used for sending messages from one application to another?
a. Server c. client
b. Mq d. webapp
9. How are java web applications packaged?
a. Jar c. war
b. Zip d. both jar and war
10. How can we connect to database in a web application?
a. oracle sql developer c. toad
b. JDBC template d. mysql
11. Which of the below can be used to debug front end of a web application?
a. Junit c. Fitnesse
b. Firebug d. Mockito
PART B(5 MARKS)
1. What is Database?
2. Explain about Java Database.
3. Enumarate/Discuss the JDBC Principles.
4. How to Interact with Database
5. Explain about how to Search in Database.
PART C(10 MARKS)
1. Explain in detail about JDBC Architecture
2. What Databases are supported in Web Applications?
3. How to Create Mutimedia Database? Explain it.
4. How to Access Data in Java.
11