AJP Unit-5
AJP Unit-5
AJP Unit-5
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers
to connect with the database.
Before JDBC, ODBC API was the database API to connect and execute query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in
Java language).
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java 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.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
The ODBC driver needs to be installed on the client machine.
2) Native-API driver
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. Oracle OCI driver is a type
2 driver.
Advantage:
Disadvantage:
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:
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:
Disadvantage:
There are 5 steps to connect any java application with the database in java using JDBC. They are
as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
The getConnection() method of DriverManager class is used to establish connection with the database
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","pas
sword");
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database. This
method returns the object of ResultSet that can be used to get all the records of a table.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
con.close();
Example:
The most popular Relational DBMS’s are Oracle, DB2, Microsoft SQL Server, and MySQL Server. We’ll
use JavaDB (a.k.a. Derby DB), which is included with your JDK. Java contains classes required for
work with DBMS in packages java.sql .
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Database1");
System.out.println("Connection established successfully");
while(rs.next())
{
System.out.println(rs.getInt("BOOK_ID") + "\t\t" + rs.getString("BOOK_NAME"));
}
stmt1.close();
stmt2.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output:
Connection established successfully
One record inserted successfully
There are two ways to connect java application with the access database.
In this example, we are going to connect the java program with the access database. In such case, we
have created the login table in the access database. There is only one column in the table named name.
Let's get all the name of the login table.
import java.sql.*;
class Test{
public static void main(String ar[])
{
Try
{
String database="student.mdb";//Here database exists in the current directory
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next())
{ System.out.println(rs.getString(1)); }
}catch(Exception ee){System.out.println(ee);}
}}
1. First open control panel-> Administrative tools-> ODBC Data Source 32Bit.
2. Switch to System DSN. System DSN lists the System Data Sources. This list shows all
system DSNs, including the name of each DSN and the driver associated with the DSN. Click
the Add button to create new Data Source See figures
Connectivity with type1 driver is not considered good. To connect java application with type1 driver,
create DSN first, here we are assuming your dsn name is mydsn.
import java.sql.*;
class Test{
public static void main(String ar[])
{
try{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next())
{ System.out.println(rs.getString(1)); }
}catch(Exception ee){System.out.println(ee);}
}}
The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers
that are available and handles establishing a connection between a database and the appropriate driver.
The DriverManager class maintains a list of Driver classes that have registered themselves by calling
the method DriverManager.registerDriver().
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be
used to get the object of Statement and DatabaseMetaData. The Connection interface provide many
methods for transaction management like commit(),rollback() etc.
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
public ResultSet executeQuery(String sql) is used to execute SELECT query. It returns the
object of ResultSet.
public int executeUpdate(String sql) is used to execute specified query, it may be
create, drop, insert, update, delete etc.
public boolean execute(String sql) is used to execute queries that may return
multiple results.
public int[] executeBatch() is used to execute batch of commands
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points
to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
public boolean next(): is used to move the cursor to the one row next from the current
position.
public boolean previous(): is used to move the cursor to the one row previous from the
current position.
public boolean first(): is used to move the cursor to the first row in result set object.
public boolean last(): is used to move the cursor to the last row in result set object.
public boolean absolute(int row): is used to move the cursor to the specified row number in the
ResultSet object.
public boolean relative(int row): is used to move the cursor to the relative row number in the
ResultSet object, it may be positive or negative.
public int getInt(int columnIndex): is used to return the data of specified column index of the
current row as int.
public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
public String getString(String is used to return the data of specified column name of the
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter
methods of PreparedStatement.
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String sets the String value to the given parameter index.
value)
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double sets the double value to the given parameter index.
value)
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an instance of
ResultSet.
Example:
import java.sql.*;
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Database1");
System.out.println("Connection established successfully");
int i=stmt1.executeUpdate();
System.out.println(i+" records inserted");
while(rs.next())
{
System.out.println(rs.getInt("BOOK_ID") + "\t\t" + rs.getString("BOOK_NAME"));
}
stmt1.close();
stmt2.close();
con.close();
}
catch(Exception e) { e.printStackTrace(); }
}
}
Output: