Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AJP Unit-5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Unit 5-Database Programming

4.1 JAVA JDBC

Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers
to connect with the database.

Why use JDBC

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).

4.2 JDBC DRIVER

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)

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.

1 Advanced java Programming


Unit 5-Database Programming

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:

 performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

 The Native driver needs to be installed on the each client machine.

2 Advanced java Programming


Unit 5-Database Programming

 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.

3 Advanced java Programming


Unit 5-Database Programming

Advantage:

 Better performance than all other drivers.


 No software is required at client side or server side.

Disadvantage:

 Drivers depends on the Database.

4.3 STEPS TO CONNECT TO THE DATABASE IN JAVA

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

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Class.forName("oracle.jdbc.driver.OracleDriver"); //for oracle connection


Class.forName (com.mysql.jdbc.Driver); //for Connection with SQL server
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver "); // for connection with MS-Access

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String password)
throws SQLException

Example to establish connection with the Oracle database

4 Advanced java Programming


Unit 5-Database Programming

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","pas
sword");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object

Statement stmt=con.createStatement();

4) Execute the query

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.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

5 Advanced java Programming


Unit 5-Database Programming

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 .

public class DBDemo


{
public static void main(String[] args)
{
ResultSet rs;
try
{

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Database1");
System.out.println("Connection established successfully");

Statement stmt1 = con.createStatement();


stmt1.executeUpdate("insert into BOOK values('103','C')");
System.out.println("One record inserted successfully");

Statement stmt2 = con.createStatement();


stmt2.executeUpdate("delete from BOOK where BOOK_ID='103'");
System.out.println("One record deleted successfully");

Statement stmt3 = con.createStatement();


stmt3.executeUpdate("update BOOK set BOOK_NAME='Linux' where
BOOK_ID='102'");

Statement stmt4 = con.createStatement();


rs = stmt4.executeQuery("select * from BOOK");

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

6 Advanced java Programming


Unit 5-Database Programming

One record deleted successfully


101 VB.Net
102 Linux
4.4 CONNECTIVITY WITH ACCESS

There are two ways to connect java application with the access database.

1. Without DSN (Data Source Name)


2. With DSN

1. Example to Connect Java Application with access without DSN

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

String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};


DBQ=" + database + ";DriverID=22;READONLY=true";

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);}

}}

2. Example to Connect Java Application with access with DSN

First create a DSN using following steps:

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

7 Advanced java Programming


Unit 5-Database Programming

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);}
}}

4.5 DRIVERMANAGER CLASS:

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().

8 Advanced java Programming


Unit 5-Database Programming

Commonly used methods of DriverManager class:

is used to register the given driver with


public static void registerDriver(Driver driver):
DriverManager.
public static void deregisterDriver(Driver is used to deregister the given driver (drop the
driver): driver from the list) with DriverManager.
public static Connection getConnection(String is used to establish the connection with the
url): specified url.
public static Connection getConnection(String is used to establish the connection with the
url,String userName,String password): specified url, username and password.

4.6 CONNECTION INTERFACE

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.

By default, connection commits the changes after executing queries.

Commonly used methods of Connection interface:

public Statement createStatement() creates a statement object that can be used to


execute SQL queries.
public Statement createStatement(int Creates a Statement object that will generate
resultSetType,int resultSetConcurrency) ResultSet objects with the given type and
concurrency.
public void setAutoCommit(boolean status) is used to set the commit status.By default it is
true.
public void commit() saves the changes made since the previous
commit/rollback permanent.
public void rollback() Drops all changes made since the previous
commit/rollback.
public void close() closes the connection and Releases a JDBC
resources immediately.

4.7 STATEMENT INTERFACE

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.

9 Advanced java Programming


Unit 5-Database Programming

Commonly used methods of Statement interface:

The important methods of Statement interface are as follows:

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

4.8 RESULTSET INTERFACE

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:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONC


UR_UPDATABLE);

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

10 Advanced java Programming


Unit 5-Database Programming

columnName): current row as String.

4.9 PREPAREDSTATEMENT INTERFACE

The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized


query. The performance of the application will be faster if you use PreparedStatement interface
because query is compiled only once.

Let's see the example of parameterized query:

String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter
methods of PreparedStatement.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

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.*;

11 Advanced java Programming


Unit 5-Database Programming

public class DBDemo1


{
public static void main(String[] args)
{
ResultSet rs;
try
{

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Database1");
System.out.println("Connection established successfully");

PreparedStatement stmt1=con.prepareStatement("insert into BOOK values(?,?)");


stmt1.setString(1,"103"); //1 specifies the first parameter in the query
stmt1.setString(2,"C");

int i=stmt1.executeUpdate();
System.out.println(i+" records inserted");

PreparedStatement stmt2=con.prepareStatement("delete from BOOK where


BOOK_ID=?");
stmt2.setString(1,"103");
int j=stmt2.executeUpdate();
System.out.println(j+" records deleted");

PreparedStatement stmt3=con.prepareStatement("update BOOK set BOOK_NAME=?


where BOOK_ID=?");
stmt3.setString(1,"Unix");
stmt3.setString(2,"102");
int k=stmt3.executeUpdate();
System.out.println(k+" records updated");

Statement st3 = con.createStatement();


rs = st3.executeQuery("select * from BOOK");

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


1 records inserted
1 records deleted
1 records updated
101 VB.Net
102 Unix

12 Advanced java Programming

You might also like