UNIT III
Java in Databases-JDBC principles –database access-Interacting-database search –Creating
multimedia databases –Database support in web applications.
Java in Databases:
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).
Microsoft SQL Server
Oracle Database
MySQL
IBM Db2
PostgreSQL
Database Languages in DBMS
1. Data Definition Language (DDL)
o DDL stands for Data Definition Language. It is used to define database structure or
pattern.
o It is used to create schema, tables, indexes, constraints, etc. in the database.
o Using the DDL statements, you can create the skeleton of the database.
o Data definition language is used to store the information of metadata like the
number of tables and schemas, their names, indexes, columns in each table,
constraints, etc.
Here are some tasks that come under DDL:
o Create: It is used to create objects in the database.
o Alter: It is used to alter the structure of the database.
o Drop: It is used to delete objects from the database.
o Truncate: It is used to remove all records from a table.
o Rename: It is used to rename an object.
o Comment: It is used to comment on the data dictionary.
These commands are used to update the database schema that's why they come under Data
definition language.
2. Data Manipulation Language (DML)
DML stands for Data Manipulation Language. It is used for accessing and manipulating data
in a database. It handles user requests.
Here are some tasks that come under DML:
o Select: It is used to retrieve data from a database.
o Insert: It is used to insert data into a table.
o Update: It is used to update existing data within a table.
o Delete: It is used to delete all records from a table.
o Merge: It performs UPSERT operation, i.e., insert or update operations.
o Call: It is used to call a structured query language or a Java subprogram.
o Explain Plan: It has the parameter of explaining data.
o Lock Table: It controls concurrency.
3. Data Control Language (DCL)
o DCL stands for Data Control Language. It is used to retrieve the stored or saved
data.
o The DCL execution is transactional. It also has rollback parameters.
(But in Oracle database, the execution of data control language does not have the
feature of rolling back.)
Here are some tasks that come under DCL:
o Grant: It is used to give user access privileges to a database.
o Revoke: It is used to take back permissions from the user.
There are the following operations which have the authorization of Revoke:
CONNECT, INSERT, USAGE, EXECUTE, DELETE, UPDATE and SELECT.
4. Transaction Control Language (TCL)
TCL is used to run the changes made by the DML statement. TCL can be grouped into a
logical transaction.
Here are some tasks that come under TCL:
o Commit: It is used to save the transaction on the database.
o Rollback: It is used to restore the database to original since the last Commit.
JDBC principles:
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database. There are
four types of JDBC drivers.
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
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 database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
A list of popular interfaces of JDBC API
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
o Clob class
o Types class
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
Database access ,Interacting with database and database search:
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
2) Create the connection object
The getConnection() method of DriverManager class is used to establish
connection with the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException
3) Create the Statement object
The createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with the
database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries
to the database. This method returns the object of ResultSet that can be used
to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
5) Close the connection object
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.
Syntax of close() method
public void close()throws SQLException
Java Database Connectivity with MySQL:
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is [Link].
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/test where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and test is the database name. We may use any database,
in such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
create database test;
use test;
create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database
1. import [Link].*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:mysql://localhost:3306/test","root","");
8. //here sonoo is database name, root is username and password
9. Statement stmt=[Link]();
10. ResultSet rs=[Link]("select * from emp");
11. while([Link]())
12. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
13. [Link]();
14. }catch(Exception e){ [Link](e);}
15. }
16. }
To connect java application with the mysql database, [Link] file is required
to be loaded.
Two ways to load the jar file:
1. Paste the [Link] file in jre/lib/ext folder
2. Set classpath
1) Paste the [Link] file in JRE/lib/ext folder:
Download the [Link] file. Go to jre/lib/ext folder and paste the
jar file here.
2) Set classpath:
There are two ways to set the classpath:
o temporary
o permanent
Temporary classpath
open command prompt and write:
C:>set classpath=c:\folder\[Link];.;
Permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the [Link] file by appending
[Link];.; as C:\folder\[Link];.;
Creating multimedia databases:
Multimedia database is a collection of multimedia data which includes text, images,
graphics (drawings, sketches), animations, audio, video, among others. These databases
have extensive amounts of data which can be multimedia and multisource. The framework
which manages these multimedia databases and their different types so that the data can
be stored, utilized, and delivered in more than one way is known as a multimedia database
management system.
The contents of a multimedia database management system can be:
1. Media data: It is the actual data which represents an object.
2. Media format data: The information such as resolution, sampling rate, encoding
system, etc. about the format of the media data under consideration after is
undergoes acquisition, processing, and encoding is the media format data.
3. Media keyword data: Media keyword data are the keyword description related to
the generation of data. This data is also known as content descriptive data.
Examples of content descriptive data are place, time, date of recording.
4. Media feature data: Media feature data contains data which is content dependent
such as kind of texture, distribution of, and the different shapes present in the data.
The types of multimedia applications that are based on the data management
characteristics are:
1. Repository applications: An extensive amount of multimedia data stored along
with metadata for retrieval purposes.
2. Presentation applications: These involve the delivery of multimedia data subject
to the temporal constraint. An optimal viewing or listening experience requires
DBMS to deliver the data at a certain rate which offers the quality of service, which
is above a particular threshold. This data is processed as it is being delivered.
3. Collaborative work using multimedia information: It involves the execution of a
complex task by merging drawings and changing notifications.
Multimedia Database Applications:
1. Documents and record management: Industries which keep a lot of documentation
and records. Ex: Insurance claim industry.
2. Knowledge dissemination: Multimedia database is an extremely efficient tool for
knowledge dissemination and providing several resources. Ex: electronic books
3. Education and training: Multimedia sources can be used to create resources useful
in education and training. These are popular sources of learning in recent days. Ex:
Digital libraries.
4. Real-time monitoring and control: Multimedia presentation when coupled with
active database technology can be an effective means for controlling and monitoring
complex tasks. Ex: Manufacture control
5. Marketing
6. Advertisement
7. Retailing
8. Entertainment
9. Travel
Database support in web applications:
Web application development agency, developers, and designers use databases to store and
organize the data that their applications need. The role of databases in web application
development has increased over time. As a result, a number of developers create applications that
use databases. You can't fully understand web application development without understanding the
role of databases. A database is nothing but an organized collection of data that helps us, whether
creating or modifying any program. Some examples of this kind of organization are the bookshelf,
the NAS storage, and even databases on your desktop computers.
The role of databases in a web application is very important. The web application interacts with
the database to store data and retrieve data from it. The database is used to store all the
information that the user needs to store. For example, if you are developing a shopping cart
website then it will contain product details, customer details, order details, etc.
Most modern web applications are based on a database. The database stores information about the
users, products, orders, and more. A database is an important component of any web
application because it provides a central location for storing user information and business logic. In
addition to this, it allows you to store complex data structures with minimal effort.
Databases are used by businesses to collect and store customer information, financial records, and
inventory data. They're also used in research projects to store information about experiments or
tests. For example, if you were conducting a survey on the habits of people who eat cereal for
breakfast, you might use a database to keep track of your results.
Databases are also used by government agencies to store public records like birth certificates and
marriage licenses. Databases are also used by medical researchers who need to record the medical
history of patients in order to determine how effective certain treatments may be for different
diseases or conditions.
Web applications are becoming more and more popular because they allow users to access
information from different devices at the same time. A web application database offers benefits
such as:
Security
A web application database provides security features such as encryption and password
protection. If a user’s password becomes lost or compromised, it will not be possible for someone
else to access the information stored in the database.
Accessibility
Users can access their data from any internet-enabled device, which includes smartphones and
tablets as well as laptops and desktops. This means that users do not have to worry about losing
their valuable data because it is stored on another device.
Reliability and scalability
Web applications are usually accessed by many users simultaneously, unlike traditional desktop
applications that are accessed by one person at a time, so web apps need to be able to handle more
requests simultaneously than their desktop counterparts. Web application databases use
distributed architecture (multiple servers) to scale up quickly when demand increases, so they can
handle large numbers of simultaneous requests without slowing down or crashing.
Ease of maintenance for IT staff
Because web application databases use distributed architecture, problems can be isolated and
fixed quickly, which reduces downtime for the end user and reduces costs for IT staffs responsible
for maintaining the system. Also, with database automation tools we can make database tasks
easier and safer.
Types of Databases in Web Application
A database is a collection of records, each of which is similar to other records in the same database.
There are two types of databases: relational and non-relational. Relational databases are built on
the principles of tabular data, which means there has to be a one-to-one relationship between the
columns and rows in the table. A non-Relational Database is also known as NoSQL Database.
Relational
A database is a large collection of structured data, which can be accessed to find specific
information. Relational databases are famous for their structure and have been used by
programmers for years.
A relational database is data storage that maintains a relationship between two or more entities. It
is used whenever you want to store information in a way that it can be retrieved by your
application. In general, we can say that a relational database is a data storage structure where each
tuple on its own occupies one record and consists of values of attributes.
There are many advantages of using relational databases over other databases. Apart from this,
there are also some disadvantages associated with using these databases which need careful
consideration before employing them for storing your data.
Advantages
The main advantages of relational databases include:
Data integrity. A correctly implemented relational database ensures that all data entered remains
accurate, complete, and consistent over time. This helps ensure that all users have access to the
most up-to-date data possible at any given moment without having to worry about whether it will
still be there when they need it later on down the line.
They're easy to use. Relational databases are designed to be easy to understand and use. The
relationships between all the tables and data elements are clearly defined, making it easy to
understand how they work together. This makes it easier for people with little or no database
experience to understand how to use them without having to learn an entirely new language.
Scalability. Relational databases scale easily from small applications up to large enterprise
systems. You can add more disk space and memory resources when needed without taking down
your application or disrupting end users. This makes relational databases ideal for large-scale
applications, such as data warehouses or customer relationship management systems.
High availability and disaster recovery capabilities. Relational databases provide automated
backup capabilities that allow you to recover quickly from hardware failures or other disasters
without requiring human intervention or manual restoration procedures. This makes relational
databases ideal for mission-critical applications where downtime is not an option.
Disadvantages
Not suitable for real-time data analysis. Relational databases can't be used for real-time data
analysis because they don't store the data in such a way that it can be queried quickly. This means
that if you want to analyze your data in real-time, you need a technology other than Relational
databases. A good example is NoSQL which is more suitable for real-time analysis because it stores
data in a different manner than relational databases do.
The inability to store documents or graphs in their native format. This means that you need
to transform your data into tabular format before storing it. This can be very inconvenient if you
want to query your data in a different way than what is supported by the database engine itself (for
example, by using SQL or Structured Query Language).
Not very good at storing sparse data (i.e., large empty spaces). For example, if you want to
store all email addresses from your customers and only non-empty addresses are stored, then this
will take up a lot of space compared to storing every single email address even if it's empty (the
latter would take less space).
Relational databases have a fixed schema. You cannot change the structure of the database
during its lifetime, this is called fixed schema. This can limit your ability to add new features or
change existing ones. For example, if you want to add a new column for an existing table in a
relational database, you will have to re-write all queries that use this table and also update all other
tables that reference this table. This can be time-consuming and error-prone.
Non-Relational
Non-relational databases (sometimes called object-oriented databases) are very different from
Relational databases. The term non-relational (or NoSQL) database describes any kind of database
in which there is no strict distinction between relations, rows, and columns. The term non-
relational comes from the fact that the objects stored within the databases are not based on
relationships (also called joins), but rather are based on an implicit, often unstructured structure.
Non-relational databases exist mainly to help solve problems relating to responsiveness,
scalability, and performance.
Non-relational databases (or NoSQL) is a class of database management systems that were
designed to be more flexible than a relational database. The main reason is that they are
disconnected from the original data structure and don't use the traditional relationships between
tables in database design which makes them easier to organize, manage, and access.
Advantages
Speed. The most obvious advantage of non-relational databases is that they can be extremely fast.
Non-relational databases can do things that would take too long in a relational database, such as
searching every record or even all records on disk, without having to query the database first.
Simplicity. Non-relational databases are generally easier to understand and use than relational
ones, making them ideal for smaller projects where there aren't many users or developers working
with the data at any given time. NoSQL databases might not be ideal for complex projects.
Scalability. Because they are not constrained by the schema, non-relational databases can scale
more easily than relational databases. You can add more hardware and therefore more nodes,
which increases the overall performance of the system. This is particularly useful when you need
to perform complex computations on large amounts of data.
Data can be stored in any format necessary for the application. For example, if your
application requires XML documents, then you can store them in an XML column instead of forcing
them into a table schema.
The processing time for queries is faster in some cases because there is no need to traverse
through multiple tables or join across multiple databases like with relational databases.
Disadvantages
No standardization. Each vendor has its own APIs and features, making it challenging to
implement cross-platform applications.
Some non-relational databases (especially those used for big data) have problems dealing
with large amounts of data at once because they don't have good query optimization algorithms
built into them as relational databases do.
A non-relational database doesn't have a fixed structure like a relational database, so you'll
need to write code that can handle the unexpected — for example, you might have to write code
that handles different field lengths depending on what kind of data is being stored. This can make it
harder to maintain your application, especially if it's being used by other people who aren't aware
of these differences.
The biggest disadvantage of non-relational databases is that they don't support ACID
transactions. In other words, to update data in a non-relational database, you need to perform
multiple queries and then combine them together. The other problem is that these databases are
not compatible with each other, so it's difficult to integrate them into a single system.
Graph Databases (NoSQL)
Graph databases are a relatively new type of database that is able to store and query complex
relationships between entities. Graph databases have been around for many years, but have
ecently become popular as large-scale applications like Facebook and LinkedIn have adopted
them.
Graph-based database management systems provide a way to model relationships between
objects as nodes connected by edges (lines). Graphs can be used to represent complex
relationships among people, places, and things in your world such as connections between people
on social media sites like Facebook.
Advantages
Easy to model real-world situations: The structure of a graph database allows you to model any
type of relationship that exists in your real-world business problem — not just the ones that fit into
a traditional table. This makes them ideal for applications such as social networks or
recommendation engines. Graphs are also great for representing complex data structures such as
trees, hierarchies, and link graphs.
Efficient for traversing linked data: Graphs are particularly useful for traversing linked data
because they allow you to follow links between objects as easily as searching within an object. You
can easily find all records related to a particular item or set of items by following related links
between those records.
Graph databases also allow you to query data on both nodes and edges at the same time, so
they're great for analyzing relationships between entities no matter how deep those relationships
may go!
Disadvantages
Performance. Graphs are not known for their fast performance. They do not perform well when
there are multiple levels of nesting or loops in the graph structure. This means that they can be
slow when dealing with large amounts of data or graphs with high-degree vertices (vertices
connected to many other vertices).
Scalability. Graphs are not scalable in an easy way like tables are in relational databases. Because
graphs are implemented as networks and each vertex can have multiple edges linking it to other
vertices, adding more vertices and edges to a graph makes it more difficult to manage efficiently.
This is especially true when each vertex has a large number of edges linking it to other vertices in
the database.
They are relatively new. Many organizations have already invested heavily in relational or
document-oriented databases and may not want to throw away all that investment. In addition,
some organizations may not need the power of a graph database because their data can be
modeled using other types of databases.
List of Popular Web App Databases
MySQL
PostgreSQL
MongoDB
Cassandra
Neo4j
MariaDB
MSSQL