SlideShare una empresa de Scribd logo
1 de 58
JDBC :
JAVA DATA BASE
CONNECTIVITY
1
stands for Java DataBase Connectivity, which is a standard
Java API for database-independent connectivity between the Java
programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks
mentioned below that are commonly associated with database
usage.
•Making a connection to a database.
•Creating SQL or MySQL statements.
•Executing SQL or MySQL queries in the database.
•Viewing & Modifying the resulting records.
JDBC - Java Database Connectivity
2
Fundamentally,
JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database.
Java can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC
driver to access a database, and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java
programs to contain database-independent code.
3
• JDBC is similar to Microsoft’s ODBC (Open Data Base
Connectivity). JDBC API makes everyday database tasks like
simple select statements very easy.
• The role of the JDBC is just to act like a wrapper to let you feed
SQL requests to the server.
• To access a database on the same machine, or a server on a LAN or
on a server across the Internet, JDBC can be used.
• What does JDBC do ?
• First, establishes a connection with a database.
• Second, sends SQL statement.
• Third is to process the results.
4
Talking to Databases
• A JDBC based application is insulated from the
characteristics of specific database engines
Java Application
JDBC
Access
Database
Oracle
Database
Sybase
Database
5
JDBC Concepts
• JDBC’s design is very similar to the design of ODBC
• Driver Manager
– Loads database drivers, and manages the connection between the
application and the driver
• Driver
– Translates API calls into operations for a specific data source
• Connection
– A session between an application and a database.
• Statement
– An SQL Statement to perform a query or update operation
6
• Metadata
– Information about returned data, the database and the driver
• ResultSet
– Logical set of columns and rows returned by executing an SQL statement
(resulting tuples: an ordered set of data)
Steps during execution
• The following steps are executed when running a
JDBC application
– Import the necessary classes
– Load the JDBC driver
– Identify the database source
– Allocate a “connection” object (create)
– Allocate a “Statement” object (create)
– Execute a query using the “Statement” object
– Retrieve data from the returned “ResultSet” object
– Close the “ResultSet” object
– Close the “Statement” object
– Close the “Connection” object
7
• The JDBC API is contained in two packages.
• The first package is called java.sql and contains core Java data
objects of the JDBC API. java.sql is part of the J2SE
• These include Java data objects that provide the basic for
connecting to the DBMS and interacting with data stored in the
DBMS.
• The second package is javax.sql, which extends java.sql and is in
J2EE.
• javax.sql includes the data objects that interact with Java Naming
and Directory Interface (JNDI) and Java data objects that manage
connection pooling, among other advanced JDBC features.
JDBC Packages
8
IMMEDIATE SOLUTIONS
JDBC Component Interaction
Driver
Manager Connection Statement ResultSet
Driver
Database
Creates Creates Creates
SQL
Result
(tuples)
Establish
Link to DB
9
• While writing any database application, the following
fundamental issues are encountered :
• The first one is creating a database. we can either create the
database outside of Java, via tools which is supplied by the database
via SQL statements fed to the database from a Java program.
• The second one is connecting to an ODBC data source. It is
registered with the ODBC driver. We can use either JDBC to ODBC
Bridge to connect to the data source in Java.
• The third one is inserting information into database. we can either
enter data outside of Java using database specific tools, or using
SQL statements sent by the Java program.
• The fourth is selectively retrieving information. we can use SQL
commands from Java to get results and then use Java to display or
manipulate that data.
10
Steps Involved in Basic JDBC Operations
Driver
Driver Manager
Connection
Statement
Result Set
1. Load the JDBC driver class:
Class.forName(“driverName”);
2. Open a database connection:
DriverManager.getConnection
(“jdbc:xxx:datasource”);
3. Issue SQL statements:
stmt = con.createStatement();
stmt.executeQuery (“Select * from myTable”);
4. Process result set:
while (rs.next()) {
name = rs.getString(“name”);
amount = rs.getInt(“amt”); }
Database
11
Two-Tier Database Access Model
• Java Application talks directly
to the database
• Accomplished through the
JDBC driver which sends
commands directly to the
database
• Results sent back directly to
the application
Application Space
Java Application
JDBC Driver
Database
SQL
Command
Result
Set
12
Three-Tier Database Access Model
• JDBC driver sends commands
to a middle tier, which in turn
sends commands to
database.
• Results are sent back to the
middle tier, which
communicates them back to
the application
Application Space
Java Application
JDBC Driver
Database
SQL
Command
Result
Set
Application Server
(middle-tier)
Proprietary
Protocol
13
JDBC Driver Types
• JDBC-ODBC Bridge, plus ODBC driver (Type 1)
– Simplest
– JDBC methods -> Translate JDBC methods to ODBC methods ->
ODBC to native methods -> Native methods API:
– First is JDBC-ODBC Bridge, which provides JDBC access via
ODBC drivers. Here the database client code must be loaded on
each client machine which uses the same driver. This kind of
driver is most appropriate on a corporate network.
• Native-API, partly Java driver (Type 2)
– JDBC methods -> Map JDBC methods to native methods (calls to
vendor library) -> Native methods API (vendor library):
– Second is a native-API partly-java driver which converts JDBC
calls into calls on the client API for oracle, Sybase, Informix,
DB2.. It requires the same binary code to be loaded on each
client machine.
14
JDBC-net, pure Java driver (Type 3)
JDBC methods -> Translate to Native API methods through
TCP/IP network -> Native API methods
Third types is a net-protocol all –Java driver that translates JDBC
calls into a DBMS independent net protocol which is subsequently,
translated to a DBMS protocol by a server. This net server
middleware is able to connect its Java clients to many different
databases.
Native-protocol, pure Java driver (Type 4)
Java methods -> Native methods in Java
• Fourth type is known as native –protocol all-java driver that
converts JDBC calls into the network protocol used by DBMSs
directly. This allows a direct call from the client machine to the
DBMS server, which is a practical solution for Intranet access.
15
Type 1: JDBC-ODBC Bridge, Plus ODBC Driver
• This driver type is provided by
Sun with JDK
• Provides JDBC access to
databases through ODBC
drivers
• ODBC driver must be
configured for the bridge to
work
• Only solution if no JDBC driver
available for the DBMS
Application Space
Java Application
JDBC – ODBC Bridge
Database
SQL
Command
Result
Set
ODBC Driver
Proprietary
Protocol
16
Type 2: Native-API, Partly Java Driver
• Native-API driver converts
JDBC commands into DBMS-
specific native calls
• Same restrictions as Type1 –
must have some binary code
loaded on its machine
• Directly interfaces with the
database
Application Space
Java Application
Type 2 JDBC Driver
Database
SQL
Command
Result
Set
Native
Database
Library
Proprietary
Protocol
17
Type 3: JDBC-Net, Pure Java Driver
• Translates JDBC calls into a
database-independent network
protocol and sent to a middleware
server.
• This server translates this DBMS-
independent protocol into a DBMS-
specific protocol and sent to the
database
• Results sent back to the
middleware and routed to the
client
Application Space
Java Application
Type 3 JDBC Driver
Database
SQL
Command
Result
Set
Middleware Space
Proprietary
Protocol
JDBC Driver
18
Type 4: Native-Protocol, Pure Java Driver
• Pure Java drivers that
communicate directly with
the vendor’s database
• JDBC commands converted
to database engine’s native
protocol directly
• Advantage: no additional
translation or middleware
layer
• Improves performance
Application Space
Java Application
Type 4 JDBC Driver
Database
SQL Command
Using Proprietary
Protocol
Result Set
Using Proprietary
Protocol
19
•J2EE components use a similar process for interacting with a
DBMS.
• This process is divided into Number of routines. These are….
• Import JDBC packages.
• Load and register the JDBC driver.
• Open a connection to the database.
• Create a statement object to perform a query.
• Execute the statement object and return a query resultset.
• Process the resultset.
• Close the resultset and statement objects.
• Close the connection.
Essential JDBC Program
20
21
Step 1. Import JDBC Packages
This is for making the JDBC API classes immediately available to the
application program. The following import statement should be included in the
program irrespective of the JDBC driver being used:
import java.sql.*;
Step 2. Load and Register the JDBC Driver
This is for establishing a communication between the JDBC program and the
Oracle database. This is done by using the static registerDriver() method of
the DriverManager class of the JDBC API. The following line of code does this job:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Step 3. Connect to the DBMS
• Once the driver is loaded, the J2EE component must connect to the
DBMS using the DriverManager.getConnection() method.
• The java.sql.DriverManager class is the highest class in the java.sql
hierarchy and is responsible for managing driver information.
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
private Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}
22
• The DriverManager.getConnection() method is passed with the
URL of the database, the user ID and the password if required by
DBMS.
• The URL is a string object that contains the driver name and the
name of the database that is being accessed by the J2EE component.
• The DriverManager.getConnection() method returns a Connection
interface that is used throughout the process to reference the
database.
• The java.sql.Connection is another interface which manages the
communication between the driver and the J2EE component.
• The java.sql.Connection interface sends statements to the DBMS
for processing.
23
Step 4 & 5. Create and Execute a SQL Statement
• Next is we have to send a SQL query to the DBMS for processing.
• A SQL query consists of a series of SQL commands that direct the
DBMS to do something such as to return a rows of data to the J2EE
component.
• Connection.createStatement() method is used to create a
Statement object.
• The Statement object is then used to execute a query and return a
ResultSet object that contains the response from the DBMS.
• Once the ResultSet is received from the DBMS, the close() method
is called to terminate the statement.
24
Statement DataRequest;
private Connection Db;
ResultSet Results;
try
{
String query = " SELECT * FROM Customers";
DataRequest = Db.createStatement();
Results=DataRequest.executeQuery(query);
DataRequest.close();
}
25
Step 6. Process Data Returned by the DBMS
• The java.sql.ResultSet object is assigned the result received from
the DBMS after the query is processed.
• The java.sql.ResultSet object consists of methods used to interact
with data that is returned by the DBMS to the J2EE component.
26
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{ System.out.println("No data returned.");
return; }
else {
while(Results.next())
{ FirstName = Results.getString(FirstName);
LastName = Results.getString(LastName);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
} }
Step 7. Terminate The Connection to the DBMS
• The connection to the DBMS is terminated by using the close()
method of the Connection object once the J2EE component is
finished accessing the DBMS.
• The close() method throws an exception if a problem is encountered
when disengaging the DBMS.
Db.close();
27
Example Program : Connecting to MS-Access
import java.sql.*;
import java.io.*;
public class DC
{
public static void main (String args[])
{
String url ="jdbc:odbc:access";
String user = " ";
String password = " ";
try
{
// load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
// create connection.
Connection c = DriverManager.getConnection(url) ;
// create statement
Statement s = c.createStatement( );
28
// execute statement and return resultset & stored in object
ResultSet r = s.executeQuery("SELECT ename, eid,
addr FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString("ename") +"," +
r.getString ("eid") +" : "+ r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
29
Example Program : Connecting to MySql
import java.sql.*;
import java.io.*;
public class DCMysql
{
public static void main (String args[])
{
String url ="jdbc:mysql://localhost:3306/sample";
String user = "root";
String password = "hemanth";
try
{
// load the driver
Class.forName("com.mysql.jdbc.Driver") ;
// create connection.
Connection c =
DriverManager.getConnection(url,user,password) ;
30
// create statement
Statement s = c.createStatement( );
// execute statement and return resultset & stored in object
ResultSet r = s.executeQuery("SELECT ename, eid, addr
FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString ("ename") +"," +
r.getString ("eid") +" : "+ r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
31
• Once a connection to the database is opened, the J2EE component
creates and sends a query to access data contained in the database.
• One of the three types of Statement objects is used to execute the
query.
1. These objects are Statement, which executes a query immediately.
2. PreparedStatement, which is used to execute a compiled query.
3. CallableStatement, which is used to execute store procedures.
Statement Objects
32
The Statement object is used whenever J2EE component needs to
immediately execute a query without first having the query
compiled.
• The Statement object contains the executeQuery() method, which
passes the query as an argument. The query is then transmitted to
the DBMS for processing.
• The executeQuery() method returns one ResultSet object that
contains rows, columns, and metadata that represents data requested
by query.
• The execute() method is used when there may be multiple results
returned. It is a boolean method which returns either true/false
• The executedUpdate() method returns an integer indicating the
number of rows that were updated by the query. 33
1. The Statement Object
• The executeUpdate() is used to INSERT, UPDATE, DELETE, and
DDL statements.
// codes showing the usage of executeQuery() method:
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim"; String password = "keogh";
Statement DataRequest; ResultSet Results; Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db = DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = “SELECT * FROM Customers”;
DataRequest = Db.createStatement();
Results = DataRequest.executeQuery(query);
// place code here to interact with the Resutls.
DataRequest.close();
}
34
• Next is how to use the executeUpdate() of the Statement object.
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
int rowsUpdated;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db = DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = “UPDATE Customers SET PAID=‘Y’WHERE
BALANCE=‘0’ ” ;
DataRequest = Db.createStatement();
rowsUpdated = DataRequest.executeUpdate(query);
DataRequest.close();
}
Db.close(); 35
A SQL query can be precompiled and executed by using the
PreparedStatement object.
• Here a query is created as usual, but a question mark is used as a
placeholder for a value that is inserted into the query after the query
is compiled.
• This statement gives you the flexibility of supplying arguments
dynamically.
• The preparedStatement() method of Connection object is called
to return the PreparedStatement object.
• The preparedStatement() method is passed the query, which is
then precompiled.
36
2. PreparedStatement Object
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
ResultSet Results;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db = DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
try
{
String query = “SELECT * FROM Customers WHERE CustNo = ? ”;
PreparedStatement pstatement = Db.prepareStatement(query);
pstatement.setString(1,”123”);
Results = pstatement.executeQuery();
// place code here to interact with the ResutlSet.
pstatement.close();
}
setString() is used to
replace the question
mark with the value
passed.
Requires two
parameters.
First an integer that
identifies the position of
the question mark
placeholder.
Second is the value that
replaces the question
mark placeholder.
37
The CallableStatement object is used to call a stored procedure
from within a J2EE object.
• A Stored procedure is a block of code and is identified by a unique
name.
• The type and style of code depends on the DBMS vendor and can
be written in PL/SQL, Transact-SQL, C, or other programming
languages.
• IN, OUT and INOUT are the three parameters used by the
CallableStatement object to call a stored procedure.
• The IN parameter contains any data that needs to be passed to the
stored procedure and whose value is assigned using the setxxx()
method.
38
3. CallableStatement
• The OUT parameter contains the value returned by the stored
procedures. The OUT parameters must be registered using the
registerOutParameter() method, later retrieved by using the getxxx()
• The INOUT parameter is a single parameter that is used to pass
information to the stored procedure and retrieve information from
the stored procedure.
Connection Db;
try
{
String query = "{CALL LastOrderNumber (?))}";
CallableStatement cstatement = Db.prepareCall(query);
cstatement.registerOutParameter(1,Types.VARCHAR);
cstatement.execute();
String lastOrderNumber = cstatement.getString(1);
cstatement.close();
}
catch (Exception e){}
Two parameters. First is an integer
represents the number of parameters, 1
means first parameter of stored
procedrue. Second is the datatype of the
value returned by the stored procedure.
39
40
Interactive SQL Tool
Interactive SQL (dbisql) is a utility for entering SQL statements.
If we use Interactive SQL to work with our database schema,
instead of executing the SQL statements one at a time, build up the
set of commands in a dbisql command file. Then we can execute this
file in dbisql to build the database.
The definitions of the database objects form the database
schema. we can think of the schema as an empty database. The SQL
statements for creating and modifying schemas are called the data
definition language (DDL).
Note: Only one user at a time can perform DDL statements on a table.
41
Interactive SQL Command File
An Interactive SQL command file is a text file with semicolons
placed at the end of commands as shown below.
CREATE TABLE t1 ( .. );
CREATE TABLE t2 ( .. );
CREATE LF INDEX i2 ON t2 ( .. );
An Interactive SQL command file usually carries the
extension .sql. To execute a command file, either paste the contents
of the file into the Interactive SQL command window (if the file has
less than 500 lines) or enter a command that reads the file into the
command window. For example, the READ statement:
read makedb
reads the Interactive SQL commands in the file makedb.sql.
The ResultSet object contains methods that are used to copy data
from the ResultSet into a Java collection object or variable for
further processsing.
• Data in a ResultSet is logically organized into a virtual table
consisting of rows and columns.
• The ResultSet uses a virtual cursor to point to a row of the virtual
table.
• The virtual cursor is positioned above the first row of data when the
ResultSet is returned by the executeQuery(). This means the virtual
cursor must be moved to the frist row using the next() method.
• The next() returns a boolean true if the row contains data; else false.
• Once the virtual cursor points to a row, the getxxx() is used to copy
data from the row to a collection, object or a variable. 42
JDBC In Action ResultSet
Reading The ResultSet
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
return;
}
else
{
while(Results.next())
{
FirstName = Results.getString(1);
LastName = Results.getString(2);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
}
43
In JDBC 2.1 API the virtual cursor can be moved backwards or
positioned at a specific row.
• Six methods are there for Resultset object. They are first(),
last(), previous(), absolute(), relative() and getrow().
• first() method moves the virtual cursor to the first row in the
Resultset.
• last() method positions the virtual cursor at the last row in the
Resultset
• previous() method moves the virtual cursor to the previous row.
• absolute() method positions the virtual cursor to a specified row
by the an integer value passed to the method.
• relative() method moves the virtual cursor the specified number of
rows contained in the parameter. 44
Scrollable Resultset
• The parameter can be positive or negative integer.
• The getRow() method returns an integer that represents the
number of the current row in the Resultset.
• To handle the scrollable ResultSet , a constant value is passed to
the Statement object that is created using the createStatement().
Three constants.
- TYPE_FORWARD_ONLY
- TYPE_SCROLL_INSENSITIVE
- TYPE_SCROLL_SENSITIVE
• TYPE_FORWARD_ONLY constant restricts the virtual cursor to
downward movement(default setting).
• The other two allow the virtual cursor to move in both directions.
45
Updatable ResultSet
• Rows contained in the ResultSet can be updatable similar to how
rows in a table can be updated.
• This is possible by passing the createStatement() method of the
Connection object the CONCUR_UPDATABLE(read & update).
• CONCUR_READ_ONLY constant can be passed to the
createStatement() method to prevent the ResultSet from being
updated.
• There are three ways in which a ResultSet can be changed.
• These are updating values in a row, deleting a row, and inserting
a new row.
• All are accomplished by using the methods of the Statement object.
46
Update ResultSet
• Once the executeQuery() of the Statement object returns a ResultSet,
the updatexxx() is used to change the value of column in the current
row of the ResultSet.
• The xxx in the updatexxx() is replaced with the data type of the
column that is to be updated.
• The updatexxx() requires two parameters. The first is either the
number or name of the column of the ResultSet that is being
updated and the second is the value that will replace the value in the
column of the ResultSet.
47
Delete Row in the ResultSet
• The deleteRow() is used to remove a row from a ResultSet.
• The deleteRow() is passed an integer that contains the number of
the row to be deleted.
• First use the absolute() method to move the virtual cursor to the row
in the Resultset that should be deleted.
• The value of that row should be examined by the program to assure
it is the proper row before the deleteRow() is called.
• The deleteRow() is then passed a zero integer indicating that the
current row must be deleted.
Resuts.deleteRow(0);
48
Insert Row in the ResultSet
• Inserting a row into the ResultSet is accomplished using basically
the same technique as is used to update the ResultSet.
• The updatexxx() is used to specify the column and value that will
place into the column of the ResultSet.
• The insertRow() is called after the updatexxx(), which causes a new
row to be inserted into the ResultSet.
49
Transaction Processing
• A transaction may involve several tasks.
• A database transaction consists of a set of SQL statements, each of
which must be successfully completed for the transaction to be
completed.
• If any one fails, then the transaction must be rolled back.
• The database transaction is not completed until the J2EE component
calls the commit() method of the Connection object.
Commit and Rollback
– Commit – a call to commit() will commit everything that was
done since the last commit was issued
– Rollback – a call to rollback() will undo any changes since the
last commit
50
51
JDBC - Batch Updates
Batch Processing allows we to group related SQL statements
into a batch and submit them with one call to the database.
When we send several SQL statements to the database at
once, we reduce the amount of communication overhead, thereby
improving performance.
JDBC drivers are not required to support this feature. we should
use the DatabaseMetaData.supportsBatchUpdates() method to
determine if the target database supports batch update processing. The
method returns true if your JDBC driver supports this feature.
52
The addBatch() method of Statement,
PreparedStatement, and CallableStatement is used to add
individual statements to the batch.
The executeBatch() is used to start the execution of all the
statements grouped together.
The executeBatch() returns an array of integers, and each element
of the array represents the update count for the respective update
statement.
we can add statements to a batch for processing, we can
remove them with the clearBatch() method.
This method removes all the statements we added with the
addBatch() method. However, we cannot selectively choose which
statement to remove.
Mapping Relational Data onto Java Objects
• Data types in SQL and the data types in Java programming
language are not identical.
• Hence for transforming data between an application using Java
types and a database using SQL types some mechanism is needed.
• The JDBC API provides three sets of methods in order to transfer
data between a database and an application written in the Java:
1. The first one is the methods on the ResultSet class for retrieving
SQL SELECT results as Java types.
2. The second one is methods on the PreparedStatement class for
sending Java types as SQL statement parameters.
3. The third one is methods on the CallableStatement class for
retrieving SQL OUT parameters as Java types.
53
Basic JDBC Data Types
• CHAR : it represents a small, fixed length character string.
• VARCHAR : it represents a small, variable-length character string.
•LONGVARCHAR : it represents a large, variable length character
string.
• BINARY : it represents a small, fixed length binary value. A 12-
byte binary types is defined by the BINARY(12). They are typically
limited upto 254 bytes.
• VARBINARY : it represents a small, variable-length binary value.
A 12-byte varialbe binary types is defined by the
VARBINARY(12). They are typically limited upto 254 bytes.
• LONGVARBINARY : it represents a large, variable length binary
value.
54
• BIT : a single bit value is represented by the JDBC type BIT that
can be zero or one.
• TINYINT : an 8-bit integer value, between 0 and 255, can be
signed or unsigned.
• SMALLINT : a 16-bit signed integer value between -32768 to
32767 is represented by type SMALLINT.
• INTEGER : a 32-bit signed integer ranging between -2147483648
to 2147483647 is represented by type INTEGER.
• BIGINT : a 64-bit signed integer value between –
9223372036854775808 to 9223372036854775807 is represented
by type BIGINT.
• REAL : A single precision floating point number that supports
seven digits of mantissa is represented by the JDBC type REAL.
55
• DOUBLE : A double precision floating point number that supports
15 digits of mantissa is represented by the JDBC type REAL.
• FLOAT : it is basically equivalent to the JDBC type DOUBLE.
• DECIMAL and NUMERIC: both are similar, represent fixed-
precision decimal values. The precision and scale parameters are
taken by these types. The precision is the total number of decimal
digits supported, and the scale is the number of decimal digit after
the decimal point.
• DATA, TIME and TIMESTAMP : these three relate to time.
• first type is knows as DATE type, represents a date consisting of
day, month and year.
• second type is knows as TIME type, represents a time and which is
consisting of hours, minutes and seconds.
• third types is known as TIMESTAMP type that represents DATE
plus TIME plus a nanosecond field.
56
• BLOB data type : BINARY LARGE OBJECT represented by type
BLOB.
• CLOB : CHARACTER LARGE OBJECT represents type CLOB.
• ARRAY : represents type ARRAY.
• DISTINCT : represents type DISTINCT field.
• STRUCT : represents type STRUCT.
• REF : represents type REF. An SQL REF references an instance of
an SQL structured type, which REF persistently and uniquely
identifies.
57
Advance JDBC Data Types
SQL Type Java Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT Boolean
TINYINT Byte
SMALLINT Short
INTEGER Integer
BIGINT Long
REAL float
FLOAT float
DOUBLE Double
BINARY Byte[]
VARBINARY Byte[]
LONGVARBINARY Byte[]
SQL Type Java Type
BLOB java.sql.Blob
CLOB java.sql.Clob
ARRAY java.sql.Array
STRUCT java.sql.Struct
REF java.sql.Ref
DATALINK java.sql.Types
DATE java.sql.date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
58

Más contenido relacionado

Similar a 4-INTERDUCATION TO JDBC-2019.ppt

Similar a 4-INTERDUCATION TO JDBC-2019.ppt (20)

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
jdbc
jdbcjdbc
jdbc
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
JDBC
JDBCJDBC
JDBC
 
Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc
jdbcjdbc
jdbc
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
 
JDBC
JDBCJDBC
JDBC
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
jdbc_unit2.ppt
jdbc_unit2.pptjdbc_unit2.ppt
jdbc_unit2.ppt
 

Último

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 

Último (20)

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 

4-INTERDUCATION TO JDBC-2019.ppt

  • 1. JDBC : JAVA DATA BASE CONNECTIVITY 1
  • 2. stands for Java DataBase Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. •Making a connection to a database. •Creating SQL or MySQL statements. •Executing SQL or MySQL queries in the database. •Viewing & Modifying the resulting records. JDBC - Java Database Connectivity 2
  • 3. Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − Java Applications Java Applets Java Servlets Java ServerPages (JSPs) Enterprise JavaBeans (EJBs). All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. 3
  • 4. • JDBC is similar to Microsoft’s ODBC (Open Data Base Connectivity). JDBC API makes everyday database tasks like simple select statements very easy. • The role of the JDBC is just to act like a wrapper to let you feed SQL requests to the server. • To access a database on the same machine, or a server on a LAN or on a server across the Internet, JDBC can be used. • What does JDBC do ? • First, establishes a connection with a database. • Second, sends SQL statement. • Third is to process the results. 4
  • 5. Talking to Databases • A JDBC based application is insulated from the characteristics of specific database engines Java Application JDBC Access Database Oracle Database Sybase Database 5
  • 6. JDBC Concepts • JDBC’s design is very similar to the design of ODBC • Driver Manager – Loads database drivers, and manages the connection between the application and the driver • Driver – Translates API calls into operations for a specific data source • Connection – A session between an application and a database. • Statement – An SQL Statement to perform a query or update operation 6 • Metadata – Information about returned data, the database and the driver • ResultSet – Logical set of columns and rows returned by executing an SQL statement (resulting tuples: an ordered set of data)
  • 7. Steps during execution • The following steps are executed when running a JDBC application – Import the necessary classes – Load the JDBC driver – Identify the database source – Allocate a “connection” object (create) – Allocate a “Statement” object (create) – Execute a query using the “Statement” object – Retrieve data from the returned “ResultSet” object – Close the “ResultSet” object – Close the “Statement” object – Close the “Connection” object 7
  • 8. • The JDBC API is contained in two packages. • The first package is called java.sql and contains core Java data objects of the JDBC API. java.sql is part of the J2SE • These include Java data objects that provide the basic for connecting to the DBMS and interacting with data stored in the DBMS. • The second package is javax.sql, which extends java.sql and is in J2EE. • javax.sql includes the data objects that interact with Java Naming and Directory Interface (JNDI) and Java data objects that manage connection pooling, among other advanced JDBC features. JDBC Packages 8 IMMEDIATE SOLUTIONS
  • 9. JDBC Component Interaction Driver Manager Connection Statement ResultSet Driver Database Creates Creates Creates SQL Result (tuples) Establish Link to DB 9
  • 10. • While writing any database application, the following fundamental issues are encountered : • The first one is creating a database. we can either create the database outside of Java, via tools which is supplied by the database via SQL statements fed to the database from a Java program. • The second one is connecting to an ODBC data source. It is registered with the ODBC driver. We can use either JDBC to ODBC Bridge to connect to the data source in Java. • The third one is inserting information into database. we can either enter data outside of Java using database specific tools, or using SQL statements sent by the Java program. • The fourth is selectively retrieving information. we can use SQL commands from Java to get results and then use Java to display or manipulate that data. 10
  • 11. Steps Involved in Basic JDBC Operations Driver Driver Manager Connection Statement Result Set 1. Load the JDBC driver class: Class.forName(“driverName”); 2. Open a database connection: DriverManager.getConnection (“jdbc:xxx:datasource”); 3. Issue SQL statements: stmt = con.createStatement(); stmt.executeQuery (“Select * from myTable”); 4. Process result set: while (rs.next()) { name = rs.getString(“name”); amount = rs.getInt(“amt”); } Database 11
  • 12. Two-Tier Database Access Model • Java Application talks directly to the database • Accomplished through the JDBC driver which sends commands directly to the database • Results sent back directly to the application Application Space Java Application JDBC Driver Database SQL Command Result Set 12
  • 13. Three-Tier Database Access Model • JDBC driver sends commands to a middle tier, which in turn sends commands to database. • Results are sent back to the middle tier, which communicates them back to the application Application Space Java Application JDBC Driver Database SQL Command Result Set Application Server (middle-tier) Proprietary Protocol 13
  • 14. JDBC Driver Types • JDBC-ODBC Bridge, plus ODBC driver (Type 1) – Simplest – JDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native methods -> Native methods API: – First is JDBC-ODBC Bridge, which provides JDBC access via ODBC drivers. Here the database client code must be loaded on each client machine which uses the same driver. This kind of driver is most appropriate on a corporate network. • Native-API, partly Java driver (Type 2) – JDBC methods -> Map JDBC methods to native methods (calls to vendor library) -> Native methods API (vendor library): – Second is a native-API partly-java driver which converts JDBC calls into calls on the client API for oracle, Sybase, Informix, DB2.. It requires the same binary code to be loaded on each client machine. 14
  • 15. JDBC-net, pure Java driver (Type 3) JDBC methods -> Translate to Native API methods through TCP/IP network -> Native API methods Third types is a net-protocol all –Java driver that translates JDBC calls into a DBMS independent net protocol which is subsequently, translated to a DBMS protocol by a server. This net server middleware is able to connect its Java clients to many different databases. Native-protocol, pure Java driver (Type 4) Java methods -> Native methods in Java • Fourth type is known as native –protocol all-java driver that converts JDBC calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server, which is a practical solution for Intranet access. 15
  • 16. Type 1: JDBC-ODBC Bridge, Plus ODBC Driver • This driver type is provided by Sun with JDK • Provides JDBC access to databases through ODBC drivers • ODBC driver must be configured for the bridge to work • Only solution if no JDBC driver available for the DBMS Application Space Java Application JDBC – ODBC Bridge Database SQL Command Result Set ODBC Driver Proprietary Protocol 16
  • 17. Type 2: Native-API, Partly Java Driver • Native-API driver converts JDBC commands into DBMS- specific native calls • Same restrictions as Type1 – must have some binary code loaded on its machine • Directly interfaces with the database Application Space Java Application Type 2 JDBC Driver Database SQL Command Result Set Native Database Library Proprietary Protocol 17
  • 18. Type 3: JDBC-Net, Pure Java Driver • Translates JDBC calls into a database-independent network protocol and sent to a middleware server. • This server translates this DBMS- independent protocol into a DBMS- specific protocol and sent to the database • Results sent back to the middleware and routed to the client Application Space Java Application Type 3 JDBC Driver Database SQL Command Result Set Middleware Space Proprietary Protocol JDBC Driver 18
  • 19. Type 4: Native-Protocol, Pure Java Driver • Pure Java drivers that communicate directly with the vendor’s database • JDBC commands converted to database engine’s native protocol directly • Advantage: no additional translation or middleware layer • Improves performance Application Space Java Application Type 4 JDBC Driver Database SQL Command Using Proprietary Protocol Result Set Using Proprietary Protocol 19
  • 20. •J2EE components use a similar process for interacting with a DBMS. • This process is divided into Number of routines. These are…. • Import JDBC packages. • Load and register the JDBC driver. • Open a connection to the database. • Create a statement object to perform a query. • Execute the statement object and return a query resultset. • Process the resultset. • Close the resultset and statement objects. • Close the connection. Essential JDBC Program 20
  • 21. 21 Step 1. Import JDBC Packages This is for making the JDBC API classes immediately available to the application program. The following import statement should be included in the program irrespective of the JDBC driver being used: import java.sql.*; Step 2. Load and Register the JDBC Driver This is for establishing a communication between the JDBC program and the Oracle database. This is done by using the static registerDriver() method of the DriverManager class of the JDBC API. The following line of code does this job: DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  • 22. Step 3. Connect to the DBMS • Once the driver is loaded, the J2EE component must connect to the DBMS using the DriverManager.getConnection() method. • The java.sql.DriverManager class is the highest class in the java.sql hierarchy and is responsible for managing driver information. String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest; private Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); } 22
  • 23. • The DriverManager.getConnection() method is passed with the URL of the database, the user ID and the password if required by DBMS. • The URL is a string object that contains the driver name and the name of the database that is being accessed by the J2EE component. • The DriverManager.getConnection() method returns a Connection interface that is used throughout the process to reference the database. • The java.sql.Connection is another interface which manages the communication between the driver and the J2EE component. • The java.sql.Connection interface sends statements to the DBMS for processing. 23
  • 24. Step 4 & 5. Create and Execute a SQL Statement • Next is we have to send a SQL query to the DBMS for processing. • A SQL query consists of a series of SQL commands that direct the DBMS to do something such as to return a rows of data to the J2EE component. • Connection.createStatement() method is used to create a Statement object. • The Statement object is then used to execute a query and return a ResultSet object that contains the response from the DBMS. • Once the ResultSet is received from the DBMS, the close() method is called to terminate the statement. 24
  • 25. Statement DataRequest; private Connection Db; ResultSet Results; try { String query = " SELECT * FROM Customers"; DataRequest = Db.createStatement(); Results=DataRequest.executeQuery(query); DataRequest.close(); } 25
  • 26. Step 6. Process Data Returned by the DBMS • The java.sql.ResultSet object is assigned the result received from the DBMS after the query is processed. • The java.sql.ResultSet object consists of methods used to interact with data that is returned by the DBMS to the J2EE component. 26 ResultSet Results; String FirstName, LastName, printrow; boolean Records = Results.next(); if(!Records) { System.out.println("No data returned."); return; } else { while(Results.next()) { FirstName = Results.getString(FirstName); LastName = Results.getString(LastName); printrow = FirstName + " " + LastName; System.out.println(printrow); } }
  • 27. Step 7. Terminate The Connection to the DBMS • The connection to the DBMS is terminated by using the close() method of the Connection object once the J2EE component is finished accessing the DBMS. • The close() method throws an exception if a problem is encountered when disengaging the DBMS. Db.close(); 27
  • 28. Example Program : Connecting to MS-Access import java.sql.*; import java.io.*; public class DC { public static void main (String args[]) { String url ="jdbc:odbc:access"; String user = " "; String password = " "; try { // load the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ; // create connection. Connection c = DriverManager.getConnection(url) ; // create statement Statement s = c.createStatement( ); 28
  • 29. // execute statement and return resultset & stored in object ResultSet r = s.executeQuery("SELECT ename, eid, addr FROM emp") ; // iterate the result set while(r.next()) { System. out.println (r.getString("ename") +"," + r.getString ("eid") +" : "+ r.getString("addr")) ; } s.close( ) ; }catch(Exception e) { System.out.println("Could not establish connection") ; } } } 29
  • 30. Example Program : Connecting to MySql import java.sql.*; import java.io.*; public class DCMysql { public static void main (String args[]) { String url ="jdbc:mysql://localhost:3306/sample"; String user = "root"; String password = "hemanth"; try { // load the driver Class.forName("com.mysql.jdbc.Driver") ; // create connection. Connection c = DriverManager.getConnection(url,user,password) ; 30
  • 31. // create statement Statement s = c.createStatement( ); // execute statement and return resultset & stored in object ResultSet r = s.executeQuery("SELECT ename, eid, addr FROM emp") ; // iterate the result set while(r.next()) { System. out.println (r.getString ("ename") +"," + r.getString ("eid") +" : "+ r.getString("addr")) ; } s.close( ) ; }catch(Exception e) { System.out.println("Could not establish connection") ; } } } 31
  • 32. • Once a connection to the database is opened, the J2EE component creates and sends a query to access data contained in the database. • One of the three types of Statement objects is used to execute the query. 1. These objects are Statement, which executes a query immediately. 2. PreparedStatement, which is used to execute a compiled query. 3. CallableStatement, which is used to execute store procedures. Statement Objects 32
  • 33. The Statement object is used whenever J2EE component needs to immediately execute a query without first having the query compiled. • The Statement object contains the executeQuery() method, which passes the query as an argument. The query is then transmitted to the DBMS for processing. • The executeQuery() method returns one ResultSet object that contains rows, columns, and metadata that represents data requested by query. • The execute() method is used when there may be multiple results returned. It is a boolean method which returns either true/false • The executedUpdate() method returns an integer indicating the number of rows that were updated by the query. 33 1. The Statement Object
  • 34. • The executeUpdate() is used to INSERT, UPDATE, DELETE, and DDL statements. // codes showing the usage of executeQuery() method: String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest; ResultSet Results; Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }catch(Exception e){} Try { String query = “SELECT * FROM Customers”; DataRequest = Db.createStatement(); Results = DataRequest.executeQuery(query); // place code here to interact with the Resutls. DataRequest.close(); } 34
  • 35. • Next is how to use the executeUpdate() of the Statement object. String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest; int rowsUpdated; Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }catch(Exception e){} Try { String query = “UPDATE Customers SET PAID=‘Y’WHERE BALANCE=‘0’ ” ; DataRequest = Db.createStatement(); rowsUpdated = DataRequest.executeUpdate(query); DataRequest.close(); } Db.close(); 35
  • 36. A SQL query can be precompiled and executed by using the PreparedStatement object. • Here a query is created as usual, but a question mark is used as a placeholder for a value that is inserted into the query after the query is compiled. • This statement gives you the flexibility of supplying arguments dynamically. • The preparedStatement() method of Connection object is called to return the PreparedStatement object. • The preparedStatement() method is passed the query, which is then precompiled. 36 2. PreparedStatement Object
  • 37. String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest; ResultSet Results; Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }catch(Exception e){} try { String query = “SELECT * FROM Customers WHERE CustNo = ? ”; PreparedStatement pstatement = Db.prepareStatement(query); pstatement.setString(1,”123”); Results = pstatement.executeQuery(); // place code here to interact with the ResutlSet. pstatement.close(); } setString() is used to replace the question mark with the value passed. Requires two parameters. First an integer that identifies the position of the question mark placeholder. Second is the value that replaces the question mark placeholder. 37
  • 38. The CallableStatement object is used to call a stored procedure from within a J2EE object. • A Stored procedure is a block of code and is identified by a unique name. • The type and style of code depends on the DBMS vendor and can be written in PL/SQL, Transact-SQL, C, or other programming languages. • IN, OUT and INOUT are the three parameters used by the CallableStatement object to call a stored procedure. • The IN parameter contains any data that needs to be passed to the stored procedure and whose value is assigned using the setxxx() method. 38 3. CallableStatement
  • 39. • The OUT parameter contains the value returned by the stored procedures. The OUT parameters must be registered using the registerOutParameter() method, later retrieved by using the getxxx() • The INOUT parameter is a single parameter that is used to pass information to the stored procedure and retrieve information from the stored procedure. Connection Db; try { String query = "{CALL LastOrderNumber (?))}"; CallableStatement cstatement = Db.prepareCall(query); cstatement.registerOutParameter(1,Types.VARCHAR); cstatement.execute(); String lastOrderNumber = cstatement.getString(1); cstatement.close(); } catch (Exception e){} Two parameters. First is an integer represents the number of parameters, 1 means first parameter of stored procedrue. Second is the datatype of the value returned by the stored procedure. 39
  • 40. 40 Interactive SQL Tool Interactive SQL (dbisql) is a utility for entering SQL statements. If we use Interactive SQL to work with our database schema, instead of executing the SQL statements one at a time, build up the set of commands in a dbisql command file. Then we can execute this file in dbisql to build the database. The definitions of the database objects form the database schema. we can think of the schema as an empty database. The SQL statements for creating and modifying schemas are called the data definition language (DDL). Note: Only one user at a time can perform DDL statements on a table.
  • 41. 41 Interactive SQL Command File An Interactive SQL command file is a text file with semicolons placed at the end of commands as shown below. CREATE TABLE t1 ( .. ); CREATE TABLE t2 ( .. ); CREATE LF INDEX i2 ON t2 ( .. ); An Interactive SQL command file usually carries the extension .sql. To execute a command file, either paste the contents of the file into the Interactive SQL command window (if the file has less than 500 lines) or enter a command that reads the file into the command window. For example, the READ statement: read makedb reads the Interactive SQL commands in the file makedb.sql.
  • 42. The ResultSet object contains methods that are used to copy data from the ResultSet into a Java collection object or variable for further processsing. • Data in a ResultSet is logically organized into a virtual table consisting of rows and columns. • The ResultSet uses a virtual cursor to point to a row of the virtual table. • The virtual cursor is positioned above the first row of data when the ResultSet is returned by the executeQuery(). This means the virtual cursor must be moved to the frist row using the next() method. • The next() returns a boolean true if the row contains data; else false. • Once the virtual cursor points to a row, the getxxx() is used to copy data from the row to a collection, object or a variable. 42 JDBC In Action ResultSet
  • 43. Reading The ResultSet ResultSet Results; String FirstName, LastName, printrow; boolean Records = Results.next(); if(!Records) { System.out.println("No data returned."); return; } else { while(Results.next()) { FirstName = Results.getString(1); LastName = Results.getString(2); printrow = FirstName + " " + LastName; System.out.println(printrow); } } 43
  • 44. In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific row. • Six methods are there for Resultset object. They are first(), last(), previous(), absolute(), relative() and getrow(). • first() method moves the virtual cursor to the first row in the Resultset. • last() method positions the virtual cursor at the last row in the Resultset • previous() method moves the virtual cursor to the previous row. • absolute() method positions the virtual cursor to a specified row by the an integer value passed to the method. • relative() method moves the virtual cursor the specified number of rows contained in the parameter. 44 Scrollable Resultset
  • 45. • The parameter can be positive or negative integer. • The getRow() method returns an integer that represents the number of the current row in the Resultset. • To handle the scrollable ResultSet , a constant value is passed to the Statement object that is created using the createStatement(). Three constants. - TYPE_FORWARD_ONLY - TYPE_SCROLL_INSENSITIVE - TYPE_SCROLL_SENSITIVE • TYPE_FORWARD_ONLY constant restricts the virtual cursor to downward movement(default setting). • The other two allow the virtual cursor to move in both directions. 45
  • 46. Updatable ResultSet • Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated. • This is possible by passing the createStatement() method of the Connection object the CONCUR_UPDATABLE(read & update). • CONCUR_READ_ONLY constant can be passed to the createStatement() method to prevent the ResultSet from being updated. • There are three ways in which a ResultSet can be changed. • These are updating values in a row, deleting a row, and inserting a new row. • All are accomplished by using the methods of the Statement object. 46
  • 47. Update ResultSet • Once the executeQuery() of the Statement object returns a ResultSet, the updatexxx() is used to change the value of column in the current row of the ResultSet. • The xxx in the updatexxx() is replaced with the data type of the column that is to be updated. • The updatexxx() requires two parameters. The first is either the number or name of the column of the ResultSet that is being updated and the second is the value that will replace the value in the column of the ResultSet. 47
  • 48. Delete Row in the ResultSet • The deleteRow() is used to remove a row from a ResultSet. • The deleteRow() is passed an integer that contains the number of the row to be deleted. • First use the absolute() method to move the virtual cursor to the row in the Resultset that should be deleted. • The value of that row should be examined by the program to assure it is the proper row before the deleteRow() is called. • The deleteRow() is then passed a zero integer indicating that the current row must be deleted. Resuts.deleteRow(0); 48
  • 49. Insert Row in the ResultSet • Inserting a row into the ResultSet is accomplished using basically the same technique as is used to update the ResultSet. • The updatexxx() is used to specify the column and value that will place into the column of the ResultSet. • The insertRow() is called after the updatexxx(), which causes a new row to be inserted into the ResultSet. 49
  • 50. Transaction Processing • A transaction may involve several tasks. • A database transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be completed. • If any one fails, then the transaction must be rolled back. • The database transaction is not completed until the J2EE component calls the commit() method of the Connection object. Commit and Rollback – Commit – a call to commit() will commit everything that was done since the last commit was issued – Rollback – a call to rollback() will undo any changes since the last commit 50
  • 51. 51 JDBC - Batch Updates Batch Processing allows we to group related SQL statements into a batch and submit them with one call to the database. When we send several SQL statements to the database at once, we reduce the amount of communication overhead, thereby improving performance. JDBC drivers are not required to support this feature. we should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • 52. 52 The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. we can add statements to a batch for processing, we can remove them with the clearBatch() method. This method removes all the statements we added with the addBatch() method. However, we cannot selectively choose which statement to remove.
  • 53. Mapping Relational Data onto Java Objects • Data types in SQL and the data types in Java programming language are not identical. • Hence for transforming data between an application using Java types and a database using SQL types some mechanism is needed. • The JDBC API provides three sets of methods in order to transfer data between a database and an application written in the Java: 1. The first one is the methods on the ResultSet class for retrieving SQL SELECT results as Java types. 2. The second one is methods on the PreparedStatement class for sending Java types as SQL statement parameters. 3. The third one is methods on the CallableStatement class for retrieving SQL OUT parameters as Java types. 53
  • 54. Basic JDBC Data Types • CHAR : it represents a small, fixed length character string. • VARCHAR : it represents a small, variable-length character string. •LONGVARCHAR : it represents a large, variable length character string. • BINARY : it represents a small, fixed length binary value. A 12- byte binary types is defined by the BINARY(12). They are typically limited upto 254 bytes. • VARBINARY : it represents a small, variable-length binary value. A 12-byte varialbe binary types is defined by the VARBINARY(12). They are typically limited upto 254 bytes. • LONGVARBINARY : it represents a large, variable length binary value. 54
  • 55. • BIT : a single bit value is represented by the JDBC type BIT that can be zero or one. • TINYINT : an 8-bit integer value, between 0 and 255, can be signed or unsigned. • SMALLINT : a 16-bit signed integer value between -32768 to 32767 is represented by type SMALLINT. • INTEGER : a 32-bit signed integer ranging between -2147483648 to 2147483647 is represented by type INTEGER. • BIGINT : a 64-bit signed integer value between – 9223372036854775808 to 9223372036854775807 is represented by type BIGINT. • REAL : A single precision floating point number that supports seven digits of mantissa is represented by the JDBC type REAL. 55
  • 56. • DOUBLE : A double precision floating point number that supports 15 digits of mantissa is represented by the JDBC type REAL. • FLOAT : it is basically equivalent to the JDBC type DOUBLE. • DECIMAL and NUMERIC: both are similar, represent fixed- precision decimal values. The precision and scale parameters are taken by these types. The precision is the total number of decimal digits supported, and the scale is the number of decimal digit after the decimal point. • DATA, TIME and TIMESTAMP : these three relate to time. • first type is knows as DATE type, represents a date consisting of day, month and year. • second type is knows as TIME type, represents a time and which is consisting of hours, minutes and seconds. • third types is known as TIMESTAMP type that represents DATE plus TIME plus a nanosecond field. 56
  • 57. • BLOB data type : BINARY LARGE OBJECT represented by type BLOB. • CLOB : CHARACTER LARGE OBJECT represents type CLOB. • ARRAY : represents type ARRAY. • DISTINCT : represents type DISTINCT field. • STRUCT : represents type STRUCT. • REF : represents type REF. An SQL REF references an instance of an SQL structured type, which REF persistently and uniquely identifies. 57 Advance JDBC Data Types
  • 58. SQL Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT Boolean TINYINT Byte SMALLINT Short INTEGER Integer BIGINT Long REAL float FLOAT float DOUBLE Double BINARY Byte[] VARBINARY Byte[] LONGVARBINARY Byte[] SQL Type Java Type BLOB java.sql.Blob CLOB java.sql.Clob ARRAY java.sql.Array STRUCT java.sql.Struct REF java.sql.Ref DATALINK java.sql.Types DATE java.sql.date TIME java.sql.Time TIMESTAMP java.sql.Timestamp 58