
Advanced Java
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
All prices
More details
Content
CHAPTER 2 - JDBC Programming
2.1 The JDBC Connectivity Model
The JDBC (Java Database Connectivity) model is a crucial aspect of advanced Java programming, facilitating interaction between Java applications and a wide range of databases. JDBC provides a standardized API for database-independent connectivity, ensuring that Java programs can access data stored in relational databases in a seamless and efficient manner.
JDBC is an API that enables Java applications to execute SQL statements, retrieve results, and propagate changes back to the database. It supports a variety of SQL operations, including querying, updating, and managing data, as well as database metadata. The JDBC API is designed to provide a common interface for database access, regardless of the underlying database management system (DBMS).
Figure 2.1
2.1.1 Components of the JDBC Connectivity Model
The JDBC Connectivity Model comprises several components that work together to enable connectivity between Java applications and a wide range of databases.
JDBC API
The JDBC API provides the application-to-JDBC Manager connection. This API includes two major sets of interfaces
i). The java.sql package contains classes and interfaces for the core JDBC API.
ii). The javax.sql package includes interfaces and classes for advanced features such as connection pooling, distributed transactions, and rowset operations.
JDBC Driver Manager
The Driver Manager is a very important part of the JDBC Connectivity Model. It can establish a connection between a Java application and the JDBC drivers. The Driver Manager is responsible for keeping track of the drivers that are available and handling requests from application to the appropriate drivers.
The DriverManager class manages a list of database drivers and establishes a connection to the database. It tries to connect to the database using the drivers listed in its internal registry.
Connection connection = DriverManager.getConnection(url, username, password);
JDBC Test Suite
This is a suite of tests that a JDBC driver must pass to ensure that the driver complies with the JDBC API.
The JDBC Test Suite consists of a series of tests designed to verify that JDBC drivers conform to the JDBC API. These tests cover a wide range of functionalities, including connection management, SQL statement execution, transaction handling, and error handling. The primary goal is to ensure that a JDBC driver can interact with a database in a consistent and predictable manner.
Components of the JDBC Test Suite
Setup and Configuration
Configuration files to specify database connection details, such as URL, username, and password.
Scripts to initialize and clean up the test database environment.
Connection Tests
Tests to validate the driver's ability to establish, maintain, and close connections.
Verification of connection properties, such as auto-commit mode and isolation levels.
Statement Tests
Tests for executing various types of SQL statements, including SELECT, INSERT, UPDATE, and DELETE.
Verification of Statement, PreparedStatement, and CallableStatement functionalities.
Transaction Tests
Tests to verify transaction management, including commit, rollback, and savepoints.
Checking behaviour under different isolation levels.
ResultSet Tests
Tests for retrieving and navigating through result sets.
Verification of cursor movement, data type retrieval, and updatability.
Metadata Tests
Tests to validate database and result set metadata retrieval.
Verification of DatabaseMetaData and ResultSetMetaData functionalities.
Error Handling Tests
Tests to ensure proper handling and reporting of SQL exceptions and warnings.
Verification of the driver's ability to handle various error scenarios gracefully.
Performance Tests
Benchmark tests to measure the performance of the driver under different workloads.
Stress tests to evaluate the driver's stability under high load conditions.
JDBC-ODBC Bridge
The JDBC-ODBC Bridge is a driver provided by the Java Development Kit (JDK) that allows Java applications to connect to databases via the Open Database Connectivity (ODBC) interface. This bridge driver translates JDBC method calls into ODBC function calls, enabling connectivity between Java applications and databases that support ODBC.
The JDBC-ODBC Bridge is known as the Type 1 JDBC driver. It is a native code driver that requires the ODBC driver to be installed on the client machine. The bridge was provided primarily to facilitate legacy database access and to allow developers to connect to databases that did not have a pure Java JDBC driver available.
Architecture
The architecture of the JDBC-ODBC Bridge involves several layers
Java Application: The application uses JDBC API to interact with the database.
JDBC-ODBC Bridge Driver: This driver translates JDBC calls into ODBC calls.
ODBC Driver Manager: Manages ODBC drivers and routes ODBC calls to the appropriate database driver.
ODBC Driver: A driver provided by the database vendor that translates ODBC calls into database-specific calls.
Database: The actual database system that processes queries and returns results.
Figure 2.2
Usage
Load the JDBC-ODBC Bridge Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Establish a Connection
String url = "jdbc:odbc:DataSourceName";
Connection connection = DriverManager.getConnection(url, "username", "password");
Create a Statement
Statement statement = connection.createStatement();
Execute a Query
ResultSet resultSet = statement.executeQuery("SELECT * FROM tablename");
Process the Result Set
while (resultSet.next()) {
System.out.println(resultSet.getString("columnname"));
}
Close the Connection
resultSet.close();
statement.close();
connection.close();
Advantages
Legacy Support: The JDBC-ODBC Bridge provides a way to connect to legacy databases that only support ODBC.
Availability: It was included in the JDK, making it readily available for developers.
Limitations
Platform Dependence: The JDBC-ODBC Bridge relies on native code and the ODBC driver, making it platform-dependent.
Performance: Due to the multiple layers of translation, performance can be slower compared to other JDBC driver types.
Security: Native code drivers can pose security risks.
Deprecation: The JDBC-ODBC Bridge was deprecated in JDK 8 and removed in JDK 9, so it is not available in modern Java environments.
Complexity: Requires proper configuration of ODBC data sources, which can be cumbersome.
2.1.2 JDBC Drivers
JDBC drivers are the core of the JDBC Connectivity Model. They are used to connect to the database. There are four types of JDBC drivers:
Type 1: JDBC-ODBC bridge driver
Type 2: Native-API/partly Java driver
Type 3: Net-protocol/all-Java driver
Type 4: Native-protocol/all-Java driver
Each type has its own advantages and disadvantages, and the choice of driver depends on the specific needs of the application and the environment.
2.1.3 Establishing a Connection
To establish a connection to a database using JDBC, the following steps are typically followed:
Load the Driver: The JDBC driver should be loaded at the beginning of the program by calling Class.forName().
Class.forName("com.mysql.jdbc.Driver");
Establish a Connection: After loading the driver, a connection should be established by using DriverManager.getConnection().
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/yourdatabase", "username", "password");
Create a Statement: Once the connection is established, a Statement object should be created to send SQL statements to the database.
Statement stmt = con.createStatement();
Execute a Query: SQL queries are executed using the Statement object created in the previous step.
ResultSet rs = stmt.executeQuery("SELECT * FROM tablename");
Process the Results: The results returned by the query should be processed.
while(rs.next()){
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
// Display values
System.out.print("ID: " + id);
System.out.println(", Name: " + name);
}
Close the Connection: Finally, it's important to close the ResultSet, Statement, and Connection objects to avoid any memory leaks.
rs.close();
stmt.close();
con.close();
2.1.4 Handling Exceptions
When dealing with database connections, it is important to handle exceptions properly. JDBC operations throw a SQLException when an error occurs during database access. The SQLException contains information such as a description of the error, an SQLSTATE code, and an error code that is specific to the database.
It is good practice to use try-catch blocks to catch SQLException and perform cleanup in the finally block.
Code-
try {
// Load driver, establish connection, create statement, execute queries
} catch(SQLException se) {
// Handle...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: ePUB
Copy protection: without DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Use a reader that can handle the file format ePUB, such as Adobe Digital Editions or FBReader – both free (see eBook Help).
- Tablet/Smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePUB works well for novels and non-fiction books – i.e., 'flowing' text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook does not use copy protection or Digital Rights Management
For more information, see our eBook Help page.