Modue5 AJAVA
Modue5 AJAVA
1. Java was not considered industrial strength programming language since java
was unable to access the DBMS.
2. Each dbms has its own way to access the data storage. low level code required
to access oracle data storage need to be rewritten to access db2.
3. 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
JDBC Architecture
Type 4 JDBC
Driver 1. Referred as Type 4 database protocol
2. SQL statements are transferred into the format required by the DBMS.
3. This is the fastest communication protocol.
JDBC Packages
JDBC API contains two packages. First package is called java.sql, second package is
called javax.sql which extends java.sql for advanced JDBC features.
Explain the various steps of the JDBC process with code snippets.
1. Loading the JDBC driver
The jdbc driver must be loaded before the J2EE compnet can be connected to
the database.
Driver is loaded by calling the method and passing it the name of driver
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Once the driver is loaded , J2EE component must connect to the DBMS using
DriverManager.getConnection() method.
It is highest class in hierarchy and is responsible for managing
driver information.
It takes three arguments URL, User, Password
It returns connection interface that is used through out the process to
reference a database
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
Statement DatRequest;
Private Connection db;
try{ Class.forName(“sun:jdbc.odbc.JdbcOdbcDrive
r”);
Db=DriverManager.getConnection(url,userId,password);
}
1 After the JDBC driver is successfully loaded and registered, the J2EE component
must connect to the database. The database must be associated with the JDBC driver.
2 The datasource that JDBC component will connect to is identified using the URL
format. The URL consists of three format.
These are jdbc which indicate jdbc protocol is used to read the URL.
<subprotocol> which is JDBC driver name.
<subname> which is the name of database.
3 Connection to the database is achieved by using one of three
getConnection() methods. It returns connection object otherwise returns
SQLException
4 Three getConnection() method
getConnection(String url)
getConnection(String url, String pass, String user)
getConnection(String url, Properties prop)
5 getConnection(String url)
Sometimes the DBMS grant access to a database to anyone that
time J2EE component uses getConnection(url) method is used.
String url=” jdbc:odbc:JdbcOdbcDriver ”;
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url);
}
try{ Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”
);
Db=DriverManager.getConnection(url,userId,password);
}
Example Program
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
Statement DatRequest;
Private Connection db;
ResultSet rs;
try{
String query=”UPDATE Customer set PAID=’Y’ where BALANCE =’0’;
DatRequest=Db.createStaement();
int n=DatRequest.executeUpdate(query);// returns no of rows updated
}catch(SQLException err)
{
System.err.println(“Error”);
System.exit(1);
}
Briefly explain the prepared statement object. Write program to call a stored
procedure.(10)
1. A SQL query must be compiled before DBMS processes the query. Query is
precompiled and executed using Prepared statements.
2. Question mark is placed as the value of the customer number. The value will be
inserted into the precompiled query later in the code.
3. Setxxx() is used to replace the question mark with the value passed to the setxxx()
method . xxx represents data type of the field.
Example if it is string then setString() is used.
4. It takes two arguments on is position of question mark and other is value to the filed.
5. This is referred as late binding.
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
ResultSet rs;
}catch(SQLException err)
{
System.err.println(“Error”);
System.exit(1);
}
Briefly explain the callable statement object. Write program to call a stored procedure.(10)
1. The callableStatement object is used to call a stored procedure from with in J2EE
object. A stored procedure is block of code and is identified by unique name. the
code can bewritten in Transact-C ,PL/SQL.
3. The callableStatement uses three types of parameter when calling stored procedure.
The parameters are IN ,OUT,INOUT.
6. INOUT parameter is used to both pass information to the stored procedure and
retrieve the information from the procedure.
BEGIN
END;
ResultSet
1. ResultSet object contain the methods that are used to copy data from
ResultSet into java collection object or variable for further
processing.
2. Data in the ResultSet is logically organized into the virtual table for further
processing. Result set along with row and column it also contains meta data.
4. J2EE component should use the virtual cursor to each row and the use other
methods of the ResultSet to object to interact with the data stored in column of
the row.
5. The virtual cursor is positioned above the first row of data when the ResultSet
is returned by executeQuery () method.
6. The virtual cursor is moved to the first row with help of next() method of
ResultSet
7. Once virtual cursor is positioned getxxx() is used to return the data. Data type
of data is represents by xxx. It should match with column data type.
stmt = conn.createStatement();
String sql;
1. Until the release of JDBC 2.1 API , the virtual cursor can move only in
forward directions. But today the virtual cursor can be positioned at a specific
row.
2. There are six methods to position the cursor at specific location in addition to next() in
scrollable result set. firs() ,last(), absolute(), relative(), previous(), and getRow().
3. first().................position at first row.
4. last()...............position at last row.
5. previous()............position at previous row.
6. absolute()….........To the row specified in the absolute function
7. relative()………… move relative to current row. Positive and negative no can be
given. Ex. relative(-4) … 4 position backward direction.
8. getRow().............returns the no of current row.
9. There are three constants can be passed to the createStatement()
10. Default is TYPE_FORWARD_ONLY. Otherwise three constant can be passed to the
create statement 1.) TYPE_SCROLL_INSENSITIVE
2.) TYPE_SCROLL_SENSITIVE
1. Rows contained in the result set is updatable similar to how rows in the table
can be updated. This is possible by sending CONCUR_UPDATABLE.
2. There are three ways in which result set can be changed. These are updating row
, deleting a row, inserting a new row.
3. Update ResultSet
Once the executeQuery() method of the statement object returns
a result set. updatexxx() method is used to change the value of
column in the current row of result set.
It requires two parameters, position of the column in query. Second
parameter is value
updateRow() method is called after all the updatexxx() methods
are called.
Example:
try{
String query= “select Fname, Lname from Customers
where Fname= ‘Mary’ and Lanme=’Smith’;
DataRequest= Db.
createStatement(ResultSet.CONCUR_UPDATABLE);
Rs= DataRequest.executeQuery(query);
Rs.updateString(“LastName”,”Smith”);
Rs.updateRow();
}
try{
String query= “select Fname, Lname from Customers
where Fname= ‘Mary’ and Lanme=’Smith’;
DataRequest= Db.
createStatement(ResultSet.CONCUR_UPDATABLE);
Rs= DataRequest.executeQuery(query);
Rs.updateString(1 ,”Jon”);
Rs.updateString(2 ,”Smith”);
Rs.insertRow();
}
6. Whatever the changes making will affect only in the result set not in the table. To
update in the table have to execute the DML( update, insert, delete) statements.
Explain the Transaction processing with example
10. Another way to combine sql statements into a single into a single transaction and
then execute the entire transaction .
11. To do this the addBatch() method of statement object. The addBatch() method receives
a SQL statement as a parameter and places the SQL statement in the batch.
12. executeBatch() method is called to execute the entire batch at the same time. It returns
an array that contains no of SQL statement that execute successfully.
String query1=”UPDATE Customers SET street =’ 5 th Main’” +
“Where Fname=’BoB’ “;
String query2=”UPDATE Customers SET street =’ 10 th Main’” +
“Where Fname=’Tom’ “;
Statement DR=DB.createStatement();
DR.addBatch(query1);
DR.addBatch(query2);
int [] updated= DR.executeBatch();
The method used to retrieve meta data information about result set are
10. getColumnCount() returns the number of columns contained in result set
SQL JDBC/Java
VARCHAR java.lang.String
CHAR java.lang.String
LONGVARCHAR java.lang.String
BIT boolean
NUMERIC java.math.BigDecimal
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT float
DOUBLE double
VARBINARY byte[ ]
BINARY byte[ ]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
CLOB java.sql.Clob
BLOB java.sql.Blob
ARRAY java.sql.Array
REF java.sql.Ref
Exception handling allows you to handle exceptional conditions such as program-defined errors
in a controlled fashion.
1. When an exception condition occurs, an exception is thrown. The term thrown
means that current program execution stops, and control is redirected to the
nearest applicable catch clause. If no applicable catch clause exists, then the
program's execution ends.
2. JDBC Exception handling is very similar to Java Excpetion handling but for
JDBC.
4. SQLException ,SQLWarnings,
DataTruncation SQLException
SQLWarnings
DataTruncation
• But, if we want to execute a single SQL statement for the multiple number of times, it’ll go
to the PreparedStatement.
Java.sql.package include classes and interface to perform almost all JDBC operation such
as creating and executing SQL queries