UNIT V Interacting With DATABASE
UNIT V Interacting With DATABASE
Total Marks=12
CH-5 INTERACTING WITH DATA BASE
• ODBC stands for Open Database Connectivity. It is basically API i.e. Application Programming Interface.
• Using ODBC driver interface created by Microsoft, an application can access the data present in
Database Management System (DBMS).
• For accessing the data from DBMS, we normally make use of Structured Query Language (SQL)
statements which is popularly known as SQL Queries.
JDBC stands for Java DataBase Connectivity. JDBC is nothing but an API
• It consists of various classes, interfaces, exceptions using which Java application can send SQL statements
to a database. The SQL is a Structured Query Language used for accessing the database.
• JDBC is useful for both application developers and JDBC driver vendors.
• The JDBC specification is prepared by Sun Microsystems. Any third party vendor can design their own JDBC
drivers using this specification. These JDBC drivers are then used by the application developers for getting connected to
the database
JDBC Architecture:
In this architecture, the HTML browser will send the command to Java Application. The Java application will then
communicate with database through JDBC API. The architecture is as shown below –
JDBC Works?
Following is a way by which JDBC works -
First of all Java application establishes connection with the data source.
1)
Then Java application invokes classes and interfaces from JDBC driver for sending queries to the data source.
2)
The JDBC driver connects to corresponding database and retrieves the result.
3)
These results are based on SQL statements which are then returned to Java application.
4)
Java application then uses the retrieved information for further processing
Types of JDBC Drivers
1. Type 1 : JDBC-ODBCBridge
2. Type 2 : Native-API/Partly Java Driver
3. Type 3 : All JAVA/ Net Protocol driver for accessing middleware server.
Type 4 : All JAVA/ Native-Protocol Pure driver Let us discuss them in detail –
4.
1) JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.
Advantages:
easy to use.
•
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
•
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls
into native calls of the database API. It is not written entirely in java.
Native-API driver
Advantage:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
No client side library is required because of application server that can perform many tasks like auditing, load balancing,
logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the
middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
Driver Interfaces
• The JDBC API is a set of classes, interfaces and exceptions used for establishing connection with data
source.
• This JDBC API is defined in the java.sql and javax.sql packages.
• We use following core JDBC classes
• The JDBC API classes are supported by the java package java.sql. Hence we must import java.sql.* in our
program.
Driver Manager Class:
• When Java application needs connection to the database it invokes the
DriverManager class.
• This class then loads JDBC drivers in the memory.
• The DriverManager also attempts to open a connection with the desired
database.
• We have to use following statement for referring the JDBC-ODBC Bridge.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
Connection Interface:
• This is an interface which represents connectivity with the data source. The connection is used for
creating the Statement instance.
• To connect, you need to get a Connection instance from JDBC. To do this, you would use the
DriverManager.getConnection() method.
Following statement can be written in your Java program to get connected with database
Thus if we write following two statements in our Java program then we can connect to the database.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
con = DriverManager.getConnection("jdbc:odbc:My_database"," ",“);
Write a Java program to simply connect with the database. Sol. :
import java.sql.*;
public class JDBCDemo
{
public static void main(String [ ] args) {
Connection con = null; try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
con = DriverManager.getConnection("jdbc:odbc:My_database"," "," ");
System.out.println("Connection Successful!");
con.close();
}
catch (ClassNotFoundException e) {
System.err.println("Exception: "+e.getMessage());
}
catch (SQLException e)
{
System.err.println("Exception: "+e.getMessage());} } }
Output:
Connection Successful!
In the above program, essentially we have to
handle two major Exceptions namely :
ClassNotFoundException and SQLException with the help of try-catch block.
Statement Interface:
• A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
• The Statement interface can not accept parameters. Creation of Statement Object
execute : It Returns true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to
1.
executeUpdate : It returns the number of rows affected by the execution of the SQL statement. Use this
2.
method to execute SQL statements using the INSERT, UPDATE or DELETE statement. The general syntax is,
executeQuery : It returns a ResultSet object. Use this method when you expect to get a result set. Normally this
3.
Callable statement
2.
Prepared Statement
∙ The java.sql.PreparedStatement interface object represents a precompiled SQL statement.
∙ This interface is used to efficiently execute SQL statements multiple times. That is when we
want to insert a record in a table by putting different values at runtime.
∙ This statement is derived from the Statement class.
∙ The PreparedStatement interface can be created by calling prepareStatement() method.
The prepareStatement() is available in java.sql.Connection interface.
The prepareStatement() method takes SQL statement in java format.
prepareStatement("insert into student values(?,?)").
where each ? represents the column index number in the table. If table student has
rollnumber and name
columns, then 1st ? refers to rollnumber, 2nd ? refers to name.
∙ After that we need to set the value to each ? by using the setter method from
PreparedStatement interface as follows:
setXXX(ColumnIndex,value)
Callable Statement
The callable statement is used when we want to access the database stored procedures. The stored procedure is
basically a block of code which is identified by unique name.
Calling Procedure
When calling the stored procedure, the CallableStatement object is used. For this object three types of parameters are
used.
You can create an instance of a CallableStatement by calling the prepareCall() method on a connection object.
Here is an example :
CallableStatement callableStatement = connection.prepareCall("{call myprocedure(?, ?)}");
ResultSet Interface
• The ResultSet interface is an important interface which is used to access the database table with general width
and unknown length.
• The table rows are retrieved in sequence using ResultSet object. Within a row its column values can be
accessed in any order.
• A ResultSet maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the
first row. The 'next' method moves the cursor to the next row.
• The ResultSet object can be created using executeQuery() method. For example
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from my_table");
Sr.
No. Methods Description
public boolean first()
1. throws SQLException Moves the cursor to the first row.
1. public void last() throws SQLException Moves the cursor to the last row.
Sr.
No. Methods Description
public boolean first()
1. throws SQLException Moves the cursor to the first row.
1. public void last() throws SQLException Moves the cursor to the last row.