You are on page 1of 45

JDBC

Implemented & Deployed by:

Prakash Gyamlani
(MCA, DAC, ‘A’ Level)
Senior Software Engineer
AmpliFlex Softwares (P) Ltd

Java DataBase Conectivity Tutorial 1


Topics
 Agenda
 What is JDBC?
 Step By Step Usage of JDBC API
 DataSource & Connection Pooling
 Transaction
 Prepared and Callable Statements

Java DataBase Conectivity Tutorial 2


What is JDBC?
 Standard Java API for accessing
relational database
 Hides database specific details from
application

Java DataBase Conectivity Tutorial 3


JDBC API
 Defines a set of Java Interfaces, which are
implemented by vendor-specific JDBC Drivers
 – Applications use this set of Java interfaces for
performing database operations – portability
 Majority of JDBC API is located in java.sql package
 – DriverManager, Connection, ResultSet,
DatabaseMetaData, ResultSetMetaData,
PreparedStatement, CallableStatement and Types.
 Other advanced functionality exists in the javax.sql
package
 – DataSource

Java DataBase Conectivity Tutorial 4


JDBC Driver
 Database specific implemention of
JDBC interfaces
 – Every database server has
corresponding JDBC driver(s)
 You can see the list of available
drivers from
 – http://industry.java.sun.com/products/jdbc/drivers

Java DataBase Conectivity Tutorial 5


Database URL
 Used to make a connection to the database
 – Can contain server, port, protocol etc…
 jdbc:subprotocol_name:driver_dependant_databas
ename
 Oracle thin driver
 jdbc:oracle:thin:@machinename:1521:dbname

 Derby
 jdbc:derby://localhost:1527/sample

 Pointbase
 jdbc:pointbase:server://localhost/sample

Java DataBase Conectivity Tutorial 6


Steps of Using JDBC
 1.Load DB-specific JDBC driver
 2.Get a Connection object
 3.Get a Statement object
 4.Execute queries and/or updates
 5.Read results
 6.Read Meta-data (optional step)
 7.Close Statement and Connection objects

Java DataBase Conectivity Tutorial 7


1. Load DB-Specific Database
Driver
 To manually load the database driver and
register it with the DriverManager, load its class
file

 – Class.forName(<database-driver>)
try {
// This loads an instance of the Pointbase DB Driver.
// The driver has to be in the classpath.

Class.forName("org.apache.derby.jdbc.ClientDriver")
;
}catch (ClassNotFoundException cnfe){
System.out.println("" + cnfe);
}

Java DataBase Conectivity Tutorial 8


2. Get a Connection Object
 DriverManager class is responsible for selecting the
database and creating the database connection.
 – Using DataSource is a prefered means of getting a
conection object (we will talk about this later)

 Create the database connection as follows:


try {
Connection connection =
DriverManager.getConnection("jdbc:derby://localhost:1527/sampl
e", “app"," app ");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}

Java DataBase Conectivity Tutorial 9


DriverManager & Connection
 java.sql.DriverManager
 getConnection(String url, String user, String
password)throws SQLException
 java.sql.Connection
 Statement createStatement() throws
SQLException
 void close() throws SQLException
 void setAutoCommit(boolean b) throws
SQLException
 void commit() throws SQLException
 void rollback() throws SQLException

Java DataBase Conectivity Tutorial 10


3. Get a Statement Object

Java DataBase Conectivity Tutorial 11


4. Executing Query or Update

Java DataBase Conectivity Tutorial 12


5. Reading Results

Java DataBase Conectivity Tutorial 13


5. Reading Results (Continued)

Java DataBase Conectivity Tutorial 14


6. Read ResultSet MetaData and
DatabaseMetaData (Optional)

Java DataBase Conectivity Tutorial 15


ResultSetMetaData Example

Java DataBase Conectivity Tutorial 16


DataSource &Connection
Pooling

Java DataBase Conectivity Tutorial 17


Sub-Topics

Java DataBase Conectivity Tutorial 18


javax.sql.DataSource Interface
and DataSource Object

Java DataBase Conectivity Tutorial 19


Properties of DataSource Object

Java DataBase Conectivity Tutorial 20


Where Are Properties of a
DataSource Defined?

• In JBOSS, they are defined in xxxx-ds.xml in


deploy folder
Java DataBase Conectivity Tutorial 21
JNDI Registration of a
DataSource (JDBC Resource)
Object

Java DataBase Conectivity Tutorial 22


JNDI Registration of a
DataSource Object

Java DataBase Conectivity Tutorial 23


Why Connection Pooling?

Java DataBase Conectivity Tutorial 24


Example: Retrieval of
DataSource Object via JNDI

Java DataBase Conectivity Tutorial 25


Code of mssql-ds.xml used in
JBOSS Server
<datasources>
<local-tx-datasource>
<jndi-name>MSSQLDS</jndi-name>
<connection-
url>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MyDatabase</
connection-url>
<driver-class>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver-class>
<user-name>x</user-name>
<password>y</password>
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>MS SQLSERVER2000</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>

Java DataBase Conectivity Tutorial 26


Code of Class which access DataSource
in case of JBOSS Server
try
{
Context ctx = new InitialContext();
DataSource ds = null ;
ds = (DataSource)ctx.lookup("java:MSSQLDS");
Connection con = ds.getConection();
}
catch(SQLException se)
{
se.printStackTrace() ;
}
catch(Exception ex)
{
ex.printStackTrace() ;
}

Java DataBase Conectivity Tutorial 27


Transaction

Java DataBase Conectivity Tutorial 28


Transaction

Java DataBase Conectivity Tutorial 29


JDBC Transaction Methods
setAutoCommit()
– If set true, every executed statement is
committed immediately
● commit()
– Relevant only if setAutoCommit(false)
– Commit operations performed since the
opening of a Connection or last commit()
or rollback() calls
● rollback()
– Relevant only if setAutoCommit(false)
– Cancels all operations performed

Java DataBase Conectivity Tutorial 30


Transactions Example
Connection connection = null;
try {
connection = ds.getConnection(); //Previously explained through
Connection Pool
connection.setAutoCommit(false);
PreparedStatement updateQty =
connection.prepareStatement("UPDATE STORE_SALES SET
QTY = ? WHERE ITEM_CODE = ? ");
int [][] arrValueToUpdate =
{ {123, 500} ,
{124, 250},
{125, 10},
{126, 350} };

Java DataBase Conectivity Tutorial 31


Transaction Example cont.
int iRecordsUpdate = 0;
for ( int items=0 ; items < arrValueToUpdate.length ;items++) {
int itemCode = arrValueToUpdate[items][0];
int qty = arrValueToUpdate[items][1];
updateQty.setInt(1,qty);
updateQty.setInt(2,itemCode);
iRecordsUpdate += updateQty.executeUpdate();
}
connection.commit();
System.out.println(iRecordsUpdate + " record(s) have been
updated");
} catch(SQLException sqle) {
System.out.println("" + sqle);

Java DataBase Conectivity Tutorial 32


Transaction Example cont.
try {
connection.rollback();
} catch(SQLException sqleRollback) {
System.out.println("" + sqleRollback);
}
}finally {
try {
connection.close();
}
catch(SQLException sqleClose) {
System.out.println("" + sqleClose);
}
}

Java DataBase Conectivity Tutorial 33


Prepared & Callable Statements
The PreparedStatement interface inherits from Statement and
differs from it in two ways:
1. Instances of PreparedStatement contain an SQL
statement that has already been compiled. This is
what makes a statement "prepared."
2. The SQL statement contained in a
PreparedStatement object may have one or more IN
parameters. An IN parameter is a parameter whose
value is not specified when the SQL statement is created.
Instead, the statement has a question mark ("?") as a
placeholder for each IN parameter. The "?" is also known
as a parameter marker. An application must set a value for
each question mark in a prepared statement before
executing the prepared statement.

Java DataBase Conectivity Tutorial 34


What Are They?

Java DataBase Conectivity Tutorial 35


PreparedStatement

Java DataBase Conectivity Tutorial 36


PreparedStatement cont.

Java DataBase Conectivity Tutorial 37


PreparedStatement Steps

Java DataBase Conectivity Tutorial 38


PreparedStatement Steps cont.

Java DataBase Conectivity Tutorial 39


PreparedStatement Steps

Java DataBase Conectivity Tutorial 40


PreparedStatement cont.

Java DataBase Conectivity Tutorial 41


CallableStatement

Java DataBase Conectivity Tutorial 42


CallableStatement cont.

Java DataBase Conectivity Tutorial 43


CallableStatement Example

Java DataBase Conectivity Tutorial 44


Thanks & Regards

Prakash Gyamlani

Java DataBase Conectivity Tutorial 45

You might also like