Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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 commonly associated with
database usage:
2.Load the JDBC driver - To load a driver, you specify the class
name of the database driver in the Class.forName method. By
doing so, you automatically create a driver instance and register
it with the JDBC driver manager.
This requires that you initialize a driver so you can open a communications channel with
the database. Following is the code snippet to achieve this:
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
3.Define the connection URL - In JDBC, a connection URL specifies the server host,
port, and database name with which to establish a connection.
This requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database as
follows:
//STEP 3: Open a connection
// Database credentials
static final String USER = "username";
When you are finished performing queries and processing results, you should
close the connection, releasing resources to the database.
You should explicitly close all database resources versus relying on the JVM's
garbage collection as follows:
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
1:
2:
3:
4:
Output:
Loan Type:
Loan Type:
Loan Type:
Loan Type:
Personal Loan
Auto Loan
Home Loan
Gold Loan
A ResultSet consists of records. Each records contains a set of columns. Each record
contains the same amount of columns, although not all columns may have a value. A column
can have a null value. Here is an illustration of a ResultSet:
This ResultSet has 3 different columns (Name, Age, Gender), and 3 records
with different values for each column.
Creating a ResultSet
You create a ResultSet by executing a Statement or PreparedStatement, like
this:
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from people");
Or like this:
String sql = "select * from people";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery();
ResultSet Types:
A ResultSet can be of a certain type. The type determines some characteristics
and abilities of the ResultSet.
Not all types are supported by all databases and JDBC drivers. You will have to
check your database and JDBC driver to see if it supports the type you want to
use. The DatabaseMetaData.supportsResultSetType(int type) method returns
true or false depending on whether the given type is supported or not. The
DatabaseMetaData class is covered in a later text.
At the time of writing there are three ResultSet types:
1. ResultSet.TYPE_FORWARD_ONLY
2. ResultSet.TYPE_SCROLL_INSENSITIVE
3. ResultSet.TYPE_SCROLL_SENSITIVE
The default type is TYPE_FORWARD_ONLY
TYPE_FORWARD_ONLY means that the ResultSet can only be navigated
forward. That is, you can only move from row 1, to row 2, to row 3 etc. You
cannot move backwards in the ResultSet.
TYPE_SCROLL_INSENSITIVE means that the ResultSet can be navigated
(scrolled) both forward and backwards. You can also jump to a position relative
to the current position, or jump to an absolute position. The ResultSet is
insensitive to changes in the underlying data source while the ResultSet is open.
That is, if a record in the ResultSet is changed in the database by another
thread or process, it will not be reflected in already opened ResulsSet's of this
type.
Description
absolute()
afterLast()
Moves the ResultSet to point after the last row in the ResultSet.
beforeFirst(
)
first()
last()
next()
previous()
relative()
Description
getRow()
Returns the row number of the current row - the row currently
pointed to by the ResultSet.
getType()
isAfterLast()
Returns true if the ResultSet points after the last row. False if
not.
isBeforeFirst(
)
Returns true if the ResultSet points before the first row. False
if not.
isFirst()
Finally the ResultSet interface also contains a method to update a row with
database changes, if the ResultSet is sensitive to change.
Method
Description
refreshRow(
)
Refreshes the column values of that row with the latest values
from the database.
SUP_I
D
101
PRIC
E
7.99
SALE
S
0
TOTA
L
0
French_Roast
49
8.99
Espresso
150
9.99
Colombian_Decaf
101
8.99
French_Roast_Dec
af
49
9.99
The following code selects the whole table and lets us see what the table
SUPPLIERS looks like:
CITY
STATE
ZIP
Delhi
95199
Mah
95460
WB
93966
101
Reliance
99 Market Street
49
Tata
1 Party Place
New
Delhi
Mumbai
150
Sahara
Kolkata
The names of the suppliers are in the table SUPPLIERS, and the names of the
coffees are in the table COFFEES. Since both tables have the column SUP_ID,
this column can be used in a join. It follows that you need some way to
distinguish which SUP_ID column you are referring to. This is done by preceding
the column name with the table name, as in "COFFEES.SUP_ID" to indicate that
you mean the column SUP_ID in the table COFFEES. The following code, in
which stmt is a Statement object, selects the coffees bought from Acme, Inc.:
String query = "
SELECT COFFEES.COF_NAME " +
"FROM COFFEES, SUPPLIERS " +
"WHERE SUPPLIERS.SUP_NAME LIKE 'Reliance' " +
"and SUPPLIERS.SUP_ID = COFFEES.SUP_ID";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Coffees bought from Reliance.: ");
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
System.out.println(" " + coffeeName);
}
This will produce the following output:
Coffees bought from Reliance.:
Colombian
Colombian_Decaf
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement
object only uses the IN parameter. The CallableStatement object can use all
three.
Parameter
IN
OUT
INOUT
Description
A parameter whose value is unknown when the SQL
statement is created. You bind values to IN parameters
with the setXXX() methods.
A parameter whose value is supplied by the SQL
statement it returns. You retrieve values from theOUT
parameters with the getXXX() methods.
A parameter that provides both input and output values.
You bind variables with the setXXX() methods and
retrieve values with the getXXX() methods.
Example1.
Suppose, you need to execute the following SQL stored procedure:
COMMIT;
END;
/
try {
dbConnection = getDBConnection();
/*Create CallableStatement Object*/
CallableStatement callableStatement = null;
catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (callableStatement != null) {
callableStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
Concurrency Types
A result set may have different update capabilities. As with scrollability, making a
ResultSet object updatable increases overhead and should be done only when
necessary. That said, it is often more convenient to make updates programmatically,
and that can only be done if a result set is made updatable. The JDBC 2.0 core API
offers two update capabilities, specified by the following constants in the ResultSet
interface:
1. CONCUR_READ_ONLY
Indicates a result set that cannot be updated programmatically
Offers the highest level of concurrency (allows the largest number of simultaneous
users). When a ResultSet object with read-only concurrency needs to set a lock, it uses
A read-only lock. This allow users to read data but not to change it. Because there is no
limit to the number of readonly locks that may be held on data at one time, there is no
limit to the number of concurrent users unless the DBMS or driver imposes one.
A ResultSet can have one of two concurrency levels:
1. ResultSet.CONCUR_READ_ONLY
2. ResultSet.CONCUR_UPDATABLE
CONCUR_READ_ONLY means that the ResultSet can only be read.
CONCUR_UPDATABLE means that the ResultSet can be both read and updated.
Example
Q.8.Transcation in JDBC?
"A transaction is a logical group of work that contains one or
more SQL statements. Either all, or none of the statements need
to be performed in order to preserve data integrity"
A complete task which is a combination of the multiple smaller tasks.
For a major task to be completed, smaller tasks need to be successfully
completed.
If any one task fails then all the previous tasks are reverted back to the
original state, means that database server guarantee to follow the ACID
(Automicity, Consistency, Isolation and Durability) properties. A
transaction is an atomic unit.
ACID Properties
Atomicity :
o Implies indivisibility
o Any indivisible operation (one which will either complete in
totally, or not at all) is said to be atomic
Consistency :
o A transaction must transition persistent data from one
consistent state to another
o In the event of a failure occurs during processing, data must
be restored to the state it was in prior to the transaction
Isolation :
o Transactions should not affect each other
o A transaction in progress, not yet committed or rolled back,
must be isolated from other transactions
Durability :
o Once a transaction commits successfully, the state changes
committed by that transaction must be durable < persistent,
despite any failures that occur afterwards
Otherwise, to roll back updates to the database made using the Connection named conn, use
the following code:
conn.rollback( );
Using SAVEPOINTS:
When you set a savepoint you define a logical rollback point within a
transaction. If an error occurs past a savepoint, you can use the rollback
method to undo either all the changes or only the changes made after
the savepoint.
The Connection object has two new methods that help you manage
savepoints:
Example:
The example below inserts a row into a table, sets the savepoint svpt1, and then inserts
a second row. When the transaction is later rolled back tosvpt1, the second insertion is
undone, but the first insertion remains intact. In other words, when the transaction is
committed, only the row containing ?FIRST? will be added to TAB1:
Statement stmt = conn.createStatement();
//First Insert Statement:
int rows = stmt.executeUpdate("INSERT INTO TAB1 (COL1) VALUES " + "(?FIRST?)");
// set savepoint
Releasing a Savepoint
The method Connection.rollback() release Savepoint takes a Savepoint
object as a parameter and removes it from the current transaction. Once a
savepoint has been released, attempting to reference it in a rollback
operation causes an SQLException to be thrown. Any savepoints that have
been created in a transaction are automatically released and become invalid
when the transaction is committed, or when the entire transaction is rolled
back. Rolling a transaction back to a savepoint automatically releases and
makes invalid any other savepoints that were created after the savepoint in
question.
Q.9. State and explain any two exception classes related to JDBC?
class
class
class
class
class
class
java.lang.Throwable
java.lang.Exception
java.sql.SQLException
java.sql.BatchUpdateException
java.sql.SQLWarning
java.sql.DataTruncation
1.SQLException:
2.BatchUpdateException:
An exception thrown when an error occurs during a batch update operation.
In addition to the information provided by SQLException, a
BatchUpdateException provides the update counts for all commands that
were executed successfully during the batch update, that is, all commands
that were executed before the error occurred. The order of elements in an
array of update counts corresponds to the order in which commands were
added to the batch.
After a command in a batch update fails to execute properly and a
BatchUpdate Exception is thrown, the driver may or may not continue to
process the remaining commands in the batch. If the driver continues
processing after a failure, the array returned by the method
BatchUpdateException.getUpdateCounts will have an element for every
command in the batch rather than only elements for the commands that
executed successfully before the error. In mthe case where the driver
continues processing commands, thearray element for any command that
failed is
Statement.EXECUTE_FAILED.
3.SQLWarning:
An exception that provides information on database access warnings.
Warnings are silently chained to the object whose method caused it to be
reported.Warnings may be retrieved from Connection, Statement, and
ResultSet objects. Trying to retrieve a warning on a connection after it has
been closed will cause an exception to be thrown. Similarly, trying to
retrieve a warning on a statement after it has been closed or on a result set
after it has been closed will cause an exception to be thrown. Note that
closing a statement also closes a result set that it might have produced.
4.DataTruncation:
An exception that reports a DataTruncation warning (on reads) or throws a
DataTruncation exception (on writes) when JDBC unexpectedly truncates a
data value.
API:
This
supports
the
JDBC
Manager-to-Driver
(JDBC Architecture)