UNIT III
A database is an organized collection of structured information, or data,
typically stored electronically in a computer system. A database is usually
controlled by a database management system (DBMS).
Data within the most common types of databases in operation today is
typically modeled in rows and columns in a series of tables to make
processing and data querying efficient. The data can then be easily
accessed, managed, modified, updated, controlled, and organized. Most
databases use structured query language (SQL) for writing and querying
data.
JDBC PRINCIPLES
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.
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 subprotocol 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.
DATABASE ACCESS
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step 1 – Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections
Java Database Connectivity
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before
using it in the program. Registration is to be done once in your program.
You can register a driver in one of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of
using new or create objects. The following example uses Class.forName() to
load the Oracle driver as shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here
we call the constructor of the driver class at compile time. The following
example uses DriverManager.registerDriver()to register the Oracle driver as
shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
user: Username from which your SQL command prompt can be
accessed.
password: password from which the SQL command prompt can be
accessed.
con: It is a reference to the Connection interface.
Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is
the IP Address where a database is stored, 1521 is the port number and xe
is the service provider. All 3 parameters above are of String type and are to
be declared by the programmer before calling the function. Use of this can
be referred to form the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The
JDBCStatement, CallableStatement, and PreparedStatement interfaces
define the methods that enable you to send SQL commands and receive
data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Note: Here, con is a reference to Connection interface used in previous step .
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here
is an SQL Query. Now we know we can have multiple types of
queries. Some of them are as follows:
The query for updating/inserting a table in a database.
The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute
queries of retrieving values from the database. This method returns the
object of ResultSet that can be used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to
execute queries of updating/inserting.
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is SQL query of the type String:
Java
// This code is for establishing connection with MySQL
// database and retrieving data
// from db Java Database connectivity
*1. import --->java.sql
*2. load and register the driver ---> com.jdbc.
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/
import java.io.*;
import java.sql.*;
class GFG {
public static void main(String[] args) throws Exception
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSet rs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db
System.out.println(name); // Print result on console
st.close(); // close statement
con.close(); // close connection
System.out.println("Connection Closed....");
Output:
Step 6: Closing the connections
So finally we have sent the data to the specified location and now we are on
the verge of completing our task. By closing the connection, objects of
Statement and ResultSet will be closed automatically. The close() method of
the Connection interface is used to close the connection. It is shown below
as follows:
con.close();
Example:
Java
import java.sql.*;
// Importing required classes
import java.util.*;
// Main class
class Main {
// Main driver method
public static void main(String a[])
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";
// Entering the data
Scanner k = new Scanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();
// Inserting data using SQL query
String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";
// Connection class object
Connection con = null;
// Try block to check for exceptions
try {
// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());
// Reference to connection interface
con = DriverManager.getConnection(url, user,
pass);
// Creating a statement
Statement st = con.createStatement();
// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");
// Closing the connections
con.close();
// Catch block to handle exceptions
catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
Output after importing data in the database:
Interface Interaction
public interface Interaction
The javax.resource.cci.Interaction enables a component to execute EIS
functions. An Interaction instance supports the following ways of interacting
with an EIS instance:
execute method that takes an input Record, output Record and an
InteractionSpec. This method executes the EIS function represented
by the InteractionSpec and updates the output Record
execute method that takes an input Record and an InteractionSpec.
This method implementation executes the EIS function represented by
the InteractionSpec and produces the output Record as a return
value.
An Interaction instance is created from a Connection and is required to
maintain its association with the Connection instance. The close method
releases all resources maintained by the resource adapter for the
Interaction. The close of an Interaction instance should not close the
associated Connection instance.
Method Summary
void clearWarnings()
Clears all the warning reported by this Interaction
instance.
void close()
Closes the current Interaction and release all the
resources held for this instance by the resource adapter.
Record execute(InteractionSpec ispec, Record input)
Executes an interaction represented by the
InteractionSpec.
boolean execute(InteractionSpec ispec, Record input, Record out
put)
Executes an interaction represented by the
InteractionSpec.
Connection getConnection()
Gets the Connection associated with the
Interaction.
ResourceWarnin getWarnings()
g Gets the first ResourceWarning from the chain of
warnings associated with this Interaction instance.
close
void close()
throws ResourceException
Closes the current Interaction and release all the resources held for
this instance by the resource adapter. The close of an Interaction
instance does not close the associated Connection instance. It is
recommended that Interaction instances be closed explicitly to free
any held resources.
Throws:
ResourceException - Failed to close the Interaction instance. Invoking
close on an already closed Interaction should also throw this
exception.
getConnection
Connection getConnection()
Gets the Connection associated with the Interaction.
Returns:
Connection instance associated with the Interaction
execute
boolean execute(InteractionSpec ispec,
Record input,
Record output)
throws ResourceException
Executes an interaction represented by the InteractionSpec. This form
of invocation takes an input Record and updates the output Record.
Parameters:
ispec - InteractionSpec representing a target EIS data/function
module
input - Input Record
output - Output Record
Returns:
true if execution of the EIS function has been successful and output
Record has been updated; false otherwise
Throws:
ResourceException - Exception if execute operation fails. Examples of
error cases are:
Resource adapter internal, EIS-specific or communication error
Invalid specification of an InteractionSpec, input or output
record structure
Errors in use of input or output Record
Invalid connection associated with this Interaction
NotSupportedException - Operation not supported
execute
Record execute(InteractionSpec ispec,
Record input)
throws ResourceException
Executes an interaction represented by the InteractionSpec. This form
of invocation takes an input Record and returns an output Record if
the execution of the Interaction has been successfull.
Parameters:
ispec - InteractionSpec representing a target EIS data/function
module
input - Input Record
Returns:
output Record if execution of the EIS function has been successful;
null otherwise
Throws:
ResourceException - Exception if execute operation fails. Examples of
error cases are:
Resource adapter internal, EIS-specific or communication error
Invalid specification of an InteractionSpec or input record
structure
Errors in use of input Record or creation of an output Record
Invalid connection associated with this Interaction
NotSupportedException - Operation not supported
getWarnings
ResourceWarning getWarnings()
throws ResourceException
Gets the first ResourceWarning from the chain of warnings associated
with this Interaction instance.
Returns:
ResourceWarning at top of the warning chain
Throws:
ResourceException - Failed to get ResourceWarnings associated with
Interaction
clearWarnings
void clearWarnings()
throws ResourceException
Clears all the warning reported by this Interaction instance. After a
call to this method, the method getWarnings will return null until a
new warning is reported for this Interaction.
Throws:
ResourceException - Failed to clear ResourceWarnings associated with
Interaction
MULTIMEDIA DATABASE
Multimedia database is 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 :
1. Media data – The actual data representing an object.
2. 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.
3. 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.
4. 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 :
1. 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.
2. 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.
3. Collaborative work using multimedia information – It involves
executing a complex task by merging drawings, changing notifications.
Example: Intelligent healthcare network.
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.
DATABASE SUPPORT IN WEB APPLICATIONS
Web Application
A web application is computer software that can be accessed using any web
browser. Usually, the frontend of a web application is created using the
scripting languages such as HTML, CSS, and JavaScript, supported by
almost all web browsers. In contrast, the backend is created by any of the
programming languages such as Java, Python, Php, etc., and databases.
Unlike the mobile application, there is no specific tool for developing web
applications; we can use any of the supported IDE for developing the web
application.
Web Server and Client
The web server is a process that handles the client's request and responds.
It processes the request made by the client by using the related protocols.
The main function of the webserver is to store the request and respond to
them with web pages. It is a medium between client and server. For
example, Apache is a leading webserver.
A client is a software that allows users to request and assist them in
communicating with the server. The web browsers are the clients in a web
application; some leading clients are Google Chrome, Firefox, Safari,
Internet Explorer, etc.
HTML and HTTP
The HTML stands for HyperText Markup Language; it is a common language
for Web Server and Web Client communication. Since both the web server
and web client are two different software components of the web, we need a
language that communicates between them.
The HTTP stands for HyperText Transfer Protocol; it is a communication
protocol between the client and the server. It runs on top of the TCP/IP
protocol.
Some of the integral components of an HTTP Request are as following:
HTTP Method: The HTTP method defines an action to be performed;
usually, they are GET, POST, PUT, etc.
URL: URL is a web address that is defined while developing a web
application. It is used to access a webpage.
Form Parameters: The form parameter is just like an argument in a Java
method. It is passed to provide the details such as user, password details on
a login page.
URL
URL stands for Universal Resource Locator used to locate the server and
resource. It is an address of a web page. Every web page on a project must
have a unique name.
A URL looks like as follows:
http://localhost:8080/SimpleWebApplication/
Where,
http or https: It is the starting point of the URL that specifies the protocol
to be used for communication.
Localhost: The localhost is the address of the server. When we run our
application locally, it is called localhost; if we deployed our project over the
web, then it is accessed by using the domain name like "javatpoint.com".
The domain name maps the server to IP addresses.
8080: This is the port number for the local server; it is optional and may
differ in different machines. If we do not manually type the port number in
the URL, then by default, the request goes to the default port of the protocol.
Usually, the port no between 0 to 1023 are reserved for some well-known
services such as HTTP, HTTPS, FTP, etc.
We have discussed all the major components of a web application. Let's
move towards our main motive How to build a web application in Java.
First, understand servlet:
What is Servlet
A Servlet is a Java program that runs within a web server; it receives the
requests and responds to them using related protocols (Usually HTTP). The
Servlets are capable enough to respond to any type of request; they are
commonly used to make the application functional.
We can create a static website using only HTML and CSS, but when it comes
to dynamic, we need a server-side programming language. For these
applications, Java provides Servlet technology, which contains HTTP-specific
servlet classes.
The javax.servlet and javax.servlet.http packages contain interfaces and
classes for creating servlets. All servlets should implement the Servlet
interface, which defines life-cycle methods. To implement a generic service,
we can use the GenericServlet class by extending it. It
provides doGet and doPost methods to handle HTTP-specific services.
steps to develop a web application:
Step1: Open Eclipse Create a Dynamic Web Project
Step2: Provide Project Name
Step3: Create a Servlet
TestServlet.java:
1. import java.io.IOException;
2. import javax.servlet.ServletException;
3. import javax.servlet.annotation.WebServlet;
4. import javax.servlet.http.HttpServlet;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7.
8. /**
9. * Servlet implementation class TestServlet
10. */
11. @WebServlet("/TestServlet")
12. public class TestServlet extends HttpServlet {
13. private static final long serialVersionUID = 1L;
14.
15. /**
16. * @see HttpServlet#HttpServlet()
17. */
18. public TestServlet() {
19. super();
20. // TODO Auto-generated constructor stub
21. }
22.
23. /**
24. * @see HttpServlet#doGet(HttpServletRequest request, HttpServlet
Response response)
25. */
26. protected void doGet(HttpServletRequest request, HttpServletResp
onse response) throws ServletException, IOException {
27. // TODO Auto-generated method stub
28. response.getWriter().append("Served at: ").append(request.getCo
ntextPath());
29. }
30.
31. /**
32. * @see HttpServlet#doPost(HttpServletRequest request, HttpServlet
Response response)
33. */
34. protected void doPost(HttpServletRequest request, HttpServletRes
ponse response) throws ServletException, IOException {
35. // TODO Auto-generated method stub
36. doGet(request, response);
37. }
38.
39. }
Step4: Add the Servlet Jar file
Step5: Create a HTML or JSP file
Step6: Map the File
Step7: Run the Application