module-3 notes
module-3 notes
JDBC
3.1.Overview of RDBMS:
RDBMS stands for Relational Database Management Systems. A database is an
organized collection of data stored in a computer system and usually controlled by a
database management system (DBMS). The data in common databases is modeled in tables,
making querying and processing efficient.
What is RDBMS?
RDBMS stands for Relational Database Management Systems. It is a program that allows
us to create, delete, and update a relational database. A Relational Database is a database
system that stores and retrieves data in a tabular format organized in the form of rows and
columns. It is a smaller subset of DBMS which was designed by E.F Codd in the 1970s.
The major DBMSs like SQL, My-SQL, and ORACLE are all based on the principles of
relational DBMS.
Relational DBMS owes its foundation to the fact that the values of each table are related to
others. It has the capability to handle larger magnitudes of data and simulate queries easily.
RDBMS History
The history of Relational Database Management Systems (RDBMS) starts in the 1970s
with E F. Codd’s work at IBM. Codd introduced the concept of relational databases in 1970
that use of SQL (Structured Query Language) for querying data. This model revolutionized
data management by emphasizing data integrity and reducing redundancy. In the 1980s,
commercial RDBMS products such as Oracle, IBM DB2, and Microsoft SQL Server
emerged, making relational databases the industry standard for data management. Over the
decades, RDBMS technology has continued to evolve, incorporating advancements in
scalability, performance, and support for complex queries, cementing its role as a
cornerstone of modern database management.
What is a Database Table?
A table is a collection of related data in an organized manner in the form of rows and
columns. It is an organized arrangement of data and information in tabular
form containing rows and columns, making it easier to understand and compare data. Here
is the pictorial representation of the table and its different components containing the data
about different students that is ID, name, Age, and course.
Database Table
Features of RDBMS
Data must be stored in tabular form in DB file, that is, it should be organized in the
form of rows and columns.
Each row of table is called record/tuple . Collection of such records is known as the
cardinality of the table
Each column of the table is called an attribute/field. Collection of such columns is
called the arity of the table.
No two records of the DB table can be same. Data duplicity is therefore avoided by
using a candidate key. Candidate Key is a minimum set of attributes required to identify
each record uniquely.
Tables are related to each other with the help for foreign keys.
Database tables also allow NULL values, that is if the values of any of the element of
the table are not filled or are missing, it becomes a NULL value, which is not equivalent
to zero. (NOTE: Primary key cannot have a NULL value).
1 Ishita A
2 Yash B
3 Ishita A
4 Mallika C
Uses of RDBMS
RDBMS is used in Customer Relationship Management.
It is used in Online Retail Platforms.
It is used in Hospital Management Systems.
It is used in Business Intelligence .
It is used in Data Warehousing
SQL Query in RDBMS
Creating a Table
Syntax:
CREATE TABLE table_name ( column1_name datatype constraint, column2_name
datatype constraint);
Example:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName
VARCHAR(50), LastName VARCHAR(50), BirthDate DATE, Salary DECIMAL(10, 2) );
2. Inserting Data into a Table
Syntax:
INSERT INTO table_name (column1_name, column2_name, …) VALUES (value1,
value2, …);
Example:
INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, Salary)
VALUES (1, ‘John’, ‘Doe’, ‘1985-06-15’, 55000.00);
3. Querying Data (SELECT)
Syntax:
SELECT column1_name, column2_name, … FROM table_name WHERE condition;
Example:
SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > 50000;
4. Deleting Data from a Table
Syntax:
DELETE FROM table_name WHERE condition;
Example:
DELETE FROM Employees WHERE EmployeeID = 1;
5. . Dropping a Table
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Employees;
Advantages of RDBMS
Easy to Manage: Each table can be independently manipulated without affecting
others.
Security: It is more secure consisting of multiple levels of security. Access of data
shared can be limited.
Flexible: Updating of data can be done at a single point without making amendments at
multiple files. Databases can easily be extended to incorporate more records, thus
providing greater scalability. Also, facilitates easy application of SQL queries.
Users: RDBMS supports client-side architecture storing multiple users together.
Facilitates storage and retrieval of large amount of data.
Easy Data Handling:
o Data fetching is faster because of relational architecture.
o Data redundancy or duplicity is avoided due to keys, indexes, and
normalization principles.
o Data consistency is ensured because RDBMS is based on ACID
properties for data transactions(Atomicity Consistency Isolation Durability).
Fault Tolerance: Replication of databases provides simultaneous access and helps the
system recover in case of disasters, such as power failures or sudden shutdowns.
Disadvantages of RDBMS
High Cost and Extensive Hardware and Software Support: Huge costs and setups
are required to make these systems functional.
Scalability: In case of addition of more data, servers along with additional power, and
memory are required.
Complexity: Voluminous data creates complexity in understanding of relations and
may lower down the performance.
Structured Limits: The fields or columns of a relational database system is enclosed
within various limits, which may lead to loss of data.
Difference Between DBMS and RDBMS
DBMS RDBMS
Data elements need to access Multiple data elements can be accessed at the
DBMS RDBMS
It deals with small quantity of data. It deals with large amount of data.
Not all Codd rules are satisfied. All 12 Codd rules are satisfied.
Data fetching is slower for the large Data fetching is fast because of relational
amount of data. approach.
Conclusion
Relational databases store data in tables. Tables can grow large and have a multitude of
columns and records. Relational database management systems (RDBMSs) use SQL (and
variants of SQL) to manage the data in these large tables. The RDBMS you use is your
choice and depends on the complexity of your application.
Here’s a simple example demonstrating the use of a Call Level Interface (CLI) in JDBC to
execute a stored procedure.
SQL Stored Procedure Example:
Sql Copy
CREATE PROCEDURE getEmployeeById(IN empId INT, OUT empName
VARCHAR(100))
BEGIN
SELECT name INTO empName
FROM employees
WHERE id = empId;
END;
Java Code Using JDBC CLI:
Java Copy
import java.sql.*;
public class JdbcCallableStatementExample {
public static void main(String[] args) {
Connection connection = null;
CallableStatement callableStatement = null;
try {
// Establish the connection to the database
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "password");
6. Retrieve Output: The result of the output parameter (empName) is retrieved using
Applications of JDBC :
• 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.
• 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
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.
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.
• The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
The socket information is then translated by the middleware application server into the call
format required by the DBMS, and forwarded to the database server.
• This kind of driver is extremely flexible, since it requires no code installed on the client and
a single driver can actually provide access to multiple databases.
• You can think of the application server as a JDBC "proxy," meaning that it makes calls for
the client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
• Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); }
catch(ClassNotFoundException ex)
{ System.out.println("Error: unable to load driver class!");
System.exit(1); }
You can use getInstance() method to work around noncompliant JVMs, but then
you'll have to code for two extra Exceptions as follows –
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
2. Approach II - DriverManager.registerDriver()
• The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
• You should use the registerDriver() method if you are using a non-JDK compliant JVM,
such as the one provided by Microsoft.
• The following example uses registerDriver() to register the Oracle driver
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);
}
All the highlighted part in URL format is static and you need to change only the
remaining part as per your database setup.
jdbc:oracle:thin:@amrood:1521:EMP
Now call getConnection() method with appropriate username and password to get
a Connection object as follows:
DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password and has
the
jdbc:oracle:driver:username/password@database
conn.close();
• Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.
The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object. This statement
gives you the flexibility of supplying arguments dynamically.
All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.
• The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive an SQLException.
• Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the parameters.
• Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database
stored procedure.
Creating CallableStatement Object
Suppose, you need to execute the following Oracle stored procedure:
Note: Above stored procedure has been written for Oracle, but we are working with MySQL
database so, let us write same stored procedure for MySQL as follows to create it in EMP
database
Three types of parameters exist: IN, OUT, and INOUT.
The PreparedStatement object only uses the IN parameter.
The CallableStatement object can use all the three. The following are the definitions:
The following code snippet shows how to employ the Connection.prepareCall() method
to instantiate a CallableStatement object based on the preceding stored procedure –
The String variable SQL, represents the stored procedure, with parameter placeholders.
• Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement, or you will receive an
SQLException.
• If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type
you are binding.
• When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method binds
the JDBC data type, to the data type that the stored procedure is expected to return.
• Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
• A simple call to the close() method will do the job. If you close the Connection object first,
it will close the CallableStatement object as well. However, you should always explicitly
close the CallableStatement object to ensure proper cleanup.
1. Scroll: Navigate through the rows of the result set, both forward and backward.
2. Update: Modify the data in the result set directly, allowing changes to be made
without having to re-query the database or recreate the result set.
Use in Databases
Scrollable and updatable result sets are commonly found in database systems and are used in
environments such as JDBC (Java Database Connectivity) or ODBC (Open Database
Connectivity), where a developer wants to interact with query results dynamically.
Key Features:
1. Scrollability: The result set is not static; you can move backward and forward
through the rows. This can be helpful in cases where you need to implement a UI
feature (like pagination) or simply need to process the result set in chunks.
o In JDBC, the result set is scrollable when you set the appropriate ResultSet
type (e.g., ResultSet.TYPE_SCROLL_INSENSITIVE or
ResultSet.TYPE_SCROLL_SENSITIVE).
oScroll operations include: first(), last(), next(), previous(), absolute(), and
relative().
2. Updating ResultSets: The ResultSet interface contains a collection of update
methods for updating the data of a result set.
• As with the get methods, there are two update methods for each data type −
▪ One that takes in a column name.
▪ One that takes in a column index.
• For example, to update a String column of the current row of a result set, you would
use one of the following updateString() methods:
There are update methods for the eight primitive data types, as well as String, Object,
URL, and the SQL data types in the java.sql package.
• Updating a row in the result set changes the columns of the current row in the
ResultSet object, but not in the underlying database. To update your changes to the row
in the database, you need to invoke one of the following methods.
The result set allows you to modify the underlying data (insert, update, delete rows) directly
in the result set. When changes are made to the result set, these changes can be committed
back to the database.
In JDBC, you can achieve updatability by specifying a ResultSet with the type
ResultSet.CONCUR_UPDATABLE. This allows you to use methods like updateString(),
updateInt(), etc., on the current row.
Practical Example:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "user",
"password");
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
// Scroll through the result set
rs.first();
System.out.println(rs.getString("name")); // Print first employee's name
// Update a row
rs.updateString("name", "John Doe");
rs.updateRow();
// Scroll to next row
rs.next();
System.out.println(rs.getString("name")); // Print updated name for the next employee
// Commit changes to the database
conn.commit();
stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO employees (name, position) VALUES ('Alice',
'Manager')");
stmt.executeUpdate("UPDATE employees SET position = 'Senior Manager' WHERE
name = 'Bob'");
try {
stmt.executeUpdate("INSERT INTO employees (name, position) VALUES ('Alice',
'Manager')");
stmt.executeUpdate("UPDATE employees SET position = 'Senior Manager' WHERE
name = 'Bob'");
XML (Extensible Markup Language) is a versatile, flexible, and widely used language for
representing structured data in a readable and self-descriptive format. It was developed by the
World Wide Web Consortium (W3C) in 1998, primarily to meet the need for data
exchange between diverse systems and applications over the internet.
Unlike HTML (HyperText Markup Language), which is focused on presentation, XML is
focused on data and is designed to be both human-readable and machine-readable.
Key Features of XML
1. Self-Descriptive:
o XML documents are made up of tags (elements) that describe the data they
contain.
o It’s easy to understand since the data is labeled in a clear structure, making it
possible for both machines and humans to comprehend.
2. Extensible:
o Unlike HTML, where predefined tags are used, XML allows you to define
your own tags. This makes it extremely flexible for various applications.
3. Hierarchical Structure:
o XML is based on a tree-like structure, where elements are nested inside each
other. The top element is often referred to as the root, and the nested elements
are called child elements.
4. Platform-Independent:
o XML is plain text and not bound to any specific programming language or
operating system. It can be processed by any device or platform that supports
XML standards.
5. Human-Readable and Machine-Readable:
o XML files are written in plain text, making them easy for humans to read and
modify. At the same time, they are structured in a way that software
applications can process automatically.
Basic XML Structure
A basic XML document consists of the following key components:
1. Prolog: This is an optional section at the beginning of the XML file that can specify
the version and encoding of the XML document.
<?xml version="1.0" encoding="UTF-8"?>
2. Elements (Tags): XML data is wrapped in tags, with the data enclosed inside the
opening <tag> and closing </tag> tags. Tags are case-sensitive.
<employee>
<name>John Doe</name>
<age>30</age>
<department>HR</department>
</employee>
<employee> is the root element.
<name>, <age>, and <department> are child elements of <employee>.
3. Attributes: Elements can have attributes that provide additional information about an
element. Attributes are placed inside the opening tag.
<employee id="101">
<name>John Doe</name>
<age>30</age>
<department>HR</department>
</employee>
4. Comments: You can add comments to XML files using <!-- -->.
<!-- This is a comment -->
<employee>
<name>John Doe</name>
</employee>
Example XML Document
Here's a simple example of an XML document:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee id="101">
<name>John Doe</name>
<age>30</age>
<department>HR</department>
</employee>
<employee id="102">
<name>Jane Smith</name>
<age>25</age>
<department>Engineering</department>
</employee>
</company>
Advantages of XML
Verbosity: XML files can be large and repetitive due to the opening and closing tags.
Performance: Parsing and processing large XML files can be slower compared to
binary formats.
Complexity: Creating and maintaining complex XML schemas or documents can
become difficult as the document size increases.
XML vs JSON:
XML is more verbose than JSON (JavaScript Object Notation), which is often
o
preferred for web APIs due to its compactness and ease of use.
o JSON is also easier to parse and manipulate in many programming languages
compared to XML.
XML vs CSV:
o CSV (Comma-Separated Values) is much simpler and smaller in size but lacks
the structure and hierarchical features of XML. XML is better suited for
representing complex relationships and nested data.
1. Complete Document in Memory: The entire XML document is loaded into memory,
so you can easily navigate, query, and modify the document.
2. Ease of Navigation: You can easily move around the document using various
methods to access different parts (e.g., elements, attributes).
3. Modification: DOM allows you to make changes to the XML document by
modifying nodes, adding new elements, and removing nodes.
1. Memory Intensive: Since the entire XML document is loaded into memory, it can be
inefficient for large XML files.
2. Slower for Large Documents: Due to the need to load and manipulate the entire
document, it can be slower for processing large XML files compared to other parsing
methods like SAX (Simple API for XML).
Common Methods and Interfaces:
1. DocumentBuilderFactory:
o newInstance(): Creates a new instance of the DocumentBuilderFactory.
o setValidating(): Enables or disables validation.
o setNamespaceAware(): Sets whether the factory is namespace-aware.
2. DocumentBuilder:
o parse(): Parses an XML file and returns a Document object.
o newDocument(): Creates a new, empty Document object.
3. Document:
o getDocumentElement(): Returns the root element of the document.
o createElement(): Creates a new element.
o getElementsByTagName(): Returns a NodeList of elements with the specified
tag name.
4. Element:
o getAttribute(): Gets the value of the attribute with the specified name.
o getElementsByTagName(): Gets child elements by tag name.
o getTextContent(): Gets the text content of an element or its children.
5. Node:
o getNodeType(): Returns the type of the node (element, text, attribute, etc.).
o getNodeName(): Returns the name of the node (e.g., "student" for an element
node).
o getChildNodes(): Returns a NodeList of child nodes.
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
// Print student information
System.out.println("Student ID: " + element.getAttribute("id"));
System.out.println("Name: "+
element.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Age: "+
element.getElementsByTagName("age").item(0).getTextContent());
System.out.println("----------");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DOM is suitable when you need to manipulate or query an entire XML document in
memory.
It is good for small to medium-sized XML files.
JAXP provides the necessary tools to parse, traverse, and manipulate XML using the
DOM model, offering flexibility and ease of use in Java.