Database Is An Organized Collection of Data. Database Management System (DBMS) Provides Mechanisms For Storing, Organizing
Database Is An Organized Collection of Data. Database Management System (DBMS) Provides Mechanisms For Storing, Organizing
Java programs interact with databases using the Java Database Connectivity (JDBC™)
API. A JDBC driver enables Java applications to connect to a database in a particular
DBMS and allows you to manipulate that database using the JDBC API.
Rows are composed of columns in which values are stored. This table consists of six
rows. The Number column of each row is the table’s primary key—a column (or group
of columns) with a value that is unique for each row.
This table associates authors with their books. The AuthorID column is a foreign key—
a column in this table that matches the primary-key column in another table.
--- A database might consist of many tables. A goal when designing a database is to
minimize the amount of duplicated data among the database’s tables. Foreign keys, which
are specified when a database table is created in the database, link the data in multiple
tables. Together the AuthorID and ISBN columns in this table form a composite primary
key. Every row in this table uniquely matches one author to one book’s ISBN.
Foreign keys also allow related data in multiple tables to be selected from those tables—
this is known as joining the data. There is a one-to-many relationship between a primary
key and a corresponding foreign key (for example, one author can write many books and
one book can be written by many authors).
is an entityrelationship (ER) diagram for the books database
The relationships in Fig. 24.9 illustrate that the sole purpose of the AuthorISBN table is
to provide a many-to-many relationship between the Authors and Titles tables—an
author can write many books, and a book can have many authors.
In most cases, it’s necessary to locate rows in a database that satisfy certain selection
criteria. Only rows that satisfy the selection criteria (formally called predicates) are
selected. SQL uses the optional WHERE clause in a query to specify the selection criteria
for the query.
Operator LIKE is used for pattern matching with wildcard characters percent (%) and
underscore (_). Pattern matching allows SQL to search for strings that match a given
pattern.
The rows in the result of a query can be sorted into ascending or descending order by
using the optional ORDER BY clause.
Note the use of the syntax tableName.columnName in the ON clause. This syntax, called
a qualified name, specifies the columns from each table that should be compared to join
the tables.
The INSERT statement inserts a row into a table.
The list of column names is followed by the SQL keyword VALUES and a comma-
separated list of values in parentheses. The values specified here must match the columns
specified after the table name in both order and type.
A SQL DELETE statement removes rows from a table. Its basic form is
This chapter’s examples use Oracle’s pure Java database Java DB, which is installed with
Oracle’s JDK on Windows, Mac OS X and Linux.
JDBC supports automatic driver discovery—it loads the database driver into memory
for you.
Lines 20–21 create a Connection object (package java.sql) referenced by connection.
The program initializes connection with the result of a call to static method
getConnection of class DriverManager (package java.sql), which attempts to connect
to the database specified by its URL.
The URL jdbc:derby:books specifies the protocol for communication (jdbc), the
subprotocol for communication (derby) and the location of the database (books). The
subprotocol derby indicates that the program uses a Java DB/Apache Derbyspecific
subprotocol to connect to the database—recall that Java DB is simply the Oracle branded
version of Apache Derby. If the DriverManager cannot connect to the database, method
getConnection throws a SQLException (package java.sql).
use the Statement object’s executeQuery method to submit a query that selects all the
author information from table Authors. This method returns an object that implements
interface ResultSet and contains the query results. The ResultSet methods enable the
program to manipulate the query result.
process the ResultSet. Line 26 obtains the ResultSet’s ResultSetMetaData (package
java.sql) object. The metadata describes the ResultSet’s contents. Programs can use
metadata programmatically to obtain information about the ResultSet’s column names
and types. Line 27 uses ResultSetMetaData method getColumnCount to retrieve the
number of columns in the ResultSet.
Method next returns boolean value true if it’s able to position to the next row; otherwise,
the method returns false.
When a ResultSet is processed, each column can be extracted as a specific Java type—
ResultSetMetaData method getColumnType returns a constant integer from class Types
(package java.sql) indicating the type of a specified column.
INTEGER, ResultSet method getInt can be used to get the column value as an int. For
simplicity, this example treats each value as an Object. We retrieve each column value
with ResultSet method getObject (line 40), then print the Object’s String representation.
The example displays the result of a query in a JTable, using a TableModel object to
provide the ResultSet data to the JTable. A JTable is a swing GUI component that can be
bound to a database to display the results of a query.
extends class AbstractTableModel (package javax.swing.table), which implements
interface TableModel
The result set type specifies whether the ResultSet’s cursor is able to scroll in both
directions or forward only and whether the ResultSet is sensitive to changes made to the
underlying data.
uses ResultSetMetaData method getColumnName to obtain the column name from the
ResultSet.
uses ResultSet method absolute to position the ResultSet cursor at a specific row.
This can be slow if the table contains many rows.] Line 159 uses ResultSet method
getRow to obtain the row number for the current row in the ResultSet.
Try entering your own queries in the text area and clicking the Submit Query button to
execute the query. Lines 161–170 register a WindowListener for the windowClosed
event, which occurs when the user closes the window. Since WindowListeners can handle
several window events, we extend class WindowAdapter and override only the
windowClosed event handler.
use the TableRowSorter class (from package javax.swing.table) to create an object that
uses our ResultSetTableModel to sort rows in the JTable that displays query results.
uses JTable method setRowSorter to specify the TableRowSorter for resultTable.
uses JTable method setRowFilter to remove any prior filter by setting the filter to null.
Otherwise, lines 140– 141 use setRowFilter to specify a RowFilter (from package
javax.swing) based on the user’s input.
The static method regexFilter receives a String containing a regular expression pattern
as its argument and an optional set of indices that specify which columns to filter.
RowSet interface, which configures the database connection and prepares query
statements automatically
. A connected RowSet object connects to the database once and remains connected while
the object is in use.
disconnected RowSet object connects to the database, executes a query to retrieve the
data from the database and then closes the connection.
When the end of the try block is reached, the trywith-resources statement invokes
JdbcRowSet method close, which closes the RowSet’s encapsulated ResultSet,
Statement and Connection.
For the preceding query, both parameters are strings that can be set with
PreparedStatement method setString
invoke Connection method prepareStatement to create the PreparedStatement named
selectAllPeople that selects all the rows in the Addresses table.
executes PreparedStatement selectAllPeople (line 60) by calling method executeQuery,
which returns a ResultSet containing the rows that match the query (in this case, all the
rows in the Addresses table).
uses PreparedStatement method executeUpdate to insert the new record.
When the user presses the Browse All Entries JButton, the
browseButtonActionPerformed handler
The user can then scroll through the entries using the Previous and Next JButtons.
When the user presses the Find JButton, the queryButtonActionPerformed handler
(lines 265–287) is called.
If there are several such entries, the user can then scroll through them using the
Previous and Next JButtons.
Such named collections of SQL statements are called stored procedures.
JDBC enables programs to invoke stored procedures using objects that implement the
interface CallableStatement.
In addition, CallableStatements can specify output parameters in which a stored
procedure can place return values.
Transaction processing enables a program that interacts with a database to treat a
database operation (or set of operations) as a single operation.