0% found this document useful (0 votes)
197 views

JDBC Word Document

Document for JDBC Concepts including various Interfaces, Classes and methods. It Contains Various Drivers Using in JDBC and Classes, Transaction Management, Batch Processing etc.

Uploaded by

Gone Harikrishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views

JDBC Word Document

Document for JDBC Concepts including various Interfaces, Classes and methods. It Contains Various Drivers Using in JDBC and Classes, Transaction Management, Batch Processing etc.

Uploaded by

Gone Harikrishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

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.

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. That is why Java has defined its own API
(JDBC API) that uses JDBC drivers.
API is a document that contains description of all the features of a product or software. It represents
classes and interfaces that software programs can follow to communicate with each other.
JDBC Driver is a software component that enables java application to interact with the database.
JDBC-ODBC bridge driver: Uses ODBC Driver to connect to the Db. It Converts JDBC method calls
to ODBC function calls.

Easy to Use & easily connected to any Db.


Performance Degraded Bcoz of Convertion and needs to be installed on the client machine.

Native-API driver (partially java 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.

performance upgraded than JDBC-ODBC bridge driver

Native Driver needs to be installed on each client machine.

Network Protocol driver (fully java driver): uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific db protocol. It is fully written in java.

No client side library is required


Network Support is required on client machine and maintenance of n/w Protocol driver
becomes costly

Thin driver (fully java 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.

Better Performance than all the Drivers and No S/w is required at client side or server side.
Drivers Depends on the Database.

There are 5 steps to connect any java application with the database in java using JDBC.
Register the Driver Class: forName() of Class class is used to register the driver class. This method
is used to dynamically load the driver class.
public static void forName(String className)throws ClassNotFoundException
Class.forName("oracle.jdbc.driver.OracleDriver");
Creating Connection: getConnection() of DriverManager class is used to establish connection with
the db.
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Creating Statement: createStatement() of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
public Statement createStatement()throws SQLException
Statement stmt=con.createStatement();
Executing Queries: executeQuery() 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.
public ResultSet executeQuery(String sql)throws SQLException
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Closing Connection: By closing connection object statement & ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
public void close()throws SQLException
con.close();
For connecting java application with the database, we need to follow 5 steps to perform database
connectivity.
Driver class is oracle.jdbc.driver.OracleDriver(or)com.mysql.jdbc.Driver
Connection URL is jdbc:oracle:thin:@localhost:1521:xe(or)jdbc:mysql://localhost:3306/db
Username & Password

DriverManager class: Acts as an interface between user & drivers. It keeps track of the drivers
that are available and handles establishing a connection between a db & the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered themselves by calling the
method DriverManager.registerDriver().
public static void registerDriver(Driver driver)
public static void deregisterDriver(Driver driver)
public static Connection getConnection(String url)
public static Connection getConnection(String url,String userName,String password)

Connection interface: 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.


public Statement createStatement()
public Statement createStatement(int resultSetType,int resultSetConcurrency)
public void setAutoCommit(boolean status)
public void commit()
public void rollback()
public void close()

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)
public int executeUpdate(String sql)
public boolean execute(String sql)
public int[] executeBatch()

ResultSet interface: 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
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

public boolean next()


public boolean previous()
public boolean first()
public boolean last()
public boolean absolute(int row)
public boolean relative(int row)
public int getInt(int columnIndex)
public int getInt(String columnName)
public String getString(int columnIndex)
public String getString(String columnName)

PreparedStatement interface: sub interface of Statement. It is used to execute


parameterized query.
String sql="insert into emp values(?,?,?)";
we are passing parameter (?) for the values. Its value will be set by calling the setter methods of
PreparedStatement.
Improves performance: Query is compiled only once.
prepareStatement() of Connection interface is used to return the object of PreparedStatement.
public PreparedStatement prepareStatement(String query)throws SQLException{}
public void setInt(int paramIndex, int value)
public void setString(int paramIndex, String value)
public void setFloat(int paramIndex, float value)
public void setDouble(int paramIndex, double value)
public int executeUpdate()
public ResultSet executeQuery()

ResultSetMetaData interface: we can get further information from the data.


If you have to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet
object.
public int getColumnCount()throws SQLException

public String getColumnName(int index)throws SQLException


public String getColumnTypeName(int index)throws SQLException
public String getTableName(int index)throws SQLException
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.
public ResultSetMetaData getMetaData()throws SQLException

DatabaseMetaData interface: provides methods to get meta data of a database such as


database product name, database product version, driver name, name of total number of tables,
name of total number of views etc.
public String getDriverName()throws SQLException
public String getDriverVersion()throws SQLException
public String getUserName()throws SQLException
public String getDatabaseProductName()throws SQLException
public String getDatabaseProductVersion()throws SQLException
public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws
SQLException
getMetaData() method of Connection interface returns the object of DatabaseMetaData.
public DatabaseMetaData getMetaData()throws SQLException

>You can store images in the database in java by the help of PreparedStatement interface.
The setBinaryStream() of PreparedStatement is used to set Binary information into parameterIndex.
Syn:

public void setBinaryStream(int paramIndex,InputStream stream)


throws SQLException
public void setBinaryStream(int paramIndex,InputStream stream,long length)
throws SQLException

For storing image into the database, BLOB (Binary Large Object) datatype is used in the table.
CREATE TABLE "IMGTABLE" ("NAME" VARCHAR2(4000), "PHOTO" BLOB);
>By the help of PreparedStatement we can retrieve and store the image in the database.
getBlob() method of PreparedStatement is used to get Binary information, it returns the instance of
Blob. After calling the getBytes() method on the blob object, we can get the array of binary
information that can be written into the image file.
public Blob getBlob()throws SQLException
)throws SQLException//Blob interface

public byte[] getBytes(long pos, int length

CREATE TABLE "IMGTABLE" ("NAME" VARCHAR2(4000), "PHOTO" BLOB);

Store file in Oracle Db: setCharacterStream () method of PreparedStatement is used to set


character information into the parameterIndex.
public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
public void setBinaryStream(int paramIndex,InputStream stream,long length)
throws SQLException
CREATE TABLE "FILETABLE"( "ID" NUMBER, "NAME" CLOB);
Retrieve file from Oracle Db: getClob() of PreparedStatement is used to get file information from
the db.
public Clob getClob(int columnIndex){}
CREATE TABLE "FILETABLE"( "ID" NUMBER, "NAME" CLOB);

CallableStatement interface: To call the stored procedures and functions.\


We can have business logic on the database by the use of stored procedures and functions that will
make the performance better because these are precompiled.
differences between stored procedures and functions:
Stored

Function

is used to perform business logic.

is used to perform calculation.

must not have the return type.

must have the return type.

may return 0 or more values.

may return only one values.

We can call functions from the procedure.

Procedure cannot be called from function.

Procedure supports input and output parameters.

Function supports only input parameter.

Exception handling using try/catch block can be


used in stored procedures.

Exception handling using try/catch block cannt


be used in user defined functions.

prepareCall() method of Connection interface returns the instance of CallableStatement.


Syn: public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
Ex: CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

Transaction Mgmt: It Represents a single unit of work.


ACID properties describes the transaction management.
Atomicity means either all successful or none
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.

Fast Performance. Bcoz, db is hit at the time of commit.

JDBC, Connection interface provides methods to manage transaction.


void setAutoCommit(boolean status)
void commit()
void commit()

Batch Processing: Instead of executing a single query, we can execute a batch (group) of
queries. The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch
processing.

Fast Performance

Methods:

void addBatch(String query)


int[] executeBatch()

Steps: Load the Driver class


Create Connection
Create statement
Add query to the batch
Execute Batch
Close Connection
JDBC RowSet: The instance of RowSet is java bean component bcoz it has properties and java bean
notification mechanism. And introduced in JDK 5.
It is the wrapper of ResultSet. It holds tabular data like ResultSet.
implementation classes of RowSet interface:

JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet

It is easy and flexible to use. And it is Scrollable & Updatable bydeafault.

To perform event handling with JdbcRowSet, you need to add the instance of RowSetListener in
the addRowSetListener method of JdbcRowSet.
public void cursorMoved(RowSetEvent event)
public void rowChanged(RowSetEvent event)
public void rowSetChanged(RowSetEvent event)

JDBC New Features:


Latest version is 4.0. Java has updated jdbc api to ease & simplify the coding to db interactivity.
Features in 3.0:
Jdbc RowSet
Savepoint in transaction management to create, rollback & release the savepoint by
Connection.setSavepoint()
Connection.rollback(Savepoint svpt)
Connection.releaseSavepoint(Savepoint svpt) methods.
Statement and ResultSet Caching for Connection Pooling we are able to reuse the statement
and result set bcoz, jdbc 3 provides you the facility of statement caching & result set caching.
Switching between Global and Local Transaction
Retrieval of auto generated keys Now you are able to get the auto generated keys by the method
getGeneratedKeys().
Features in 4.0:
Automatic Loading of Driver class we don't need to write Class.forName() now because it is loaded
bydefault since jdbc4.
Subclasses of SQLException Jdbc 4 provides new subclasses of SQLException class for better
readability and handling.
New methods There are many new methods introduced in Connection, PreparedStatement,
CallableStatement, ResultSet etc.
Improved DataSource Now data source implementation is improved.

Event Handling support in Statement for Connection Pooling Now Connection Pooling can listen
statement error and statement closing events.

Servlet

You might also like