Está en la página 1de 26

JDBC

1. INTRODUCTION

2. JDBC DRIVERS

3. SEVEN STEPS USING JDBC DRIVERS

4. PROPERTIES OF RESULSET

5. USING DIFFERENT STATEMENTS

6. HANDLING SQL EXCEPTIONS

7. SUBMITTING MULTIPLE TSTATEMENT AS A SINGLE TRANSACTION

8. JDBC DATA TYPES

9.

Prepared by: Praveen Kumar Mishra 1

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


INTRODUCTION

JDBC is a set of classes and interfaces written in Java to allow other Java programs
to send SQL statements to a relational database management system.

A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-
specific APIs. A driver is nothing but an implementation of various interfaces
specified in java.sql and javax.sql packages.

JDBC API provides developers a way to connect to relational data from within java
code. Using the JDBC API developers can create a client (which can be anything from
an applet to an EJB) that can connect to a database, execute SQL statements and
processes that result of this statement.

Version 2.0 of the JDBC API had two parts: the JDBC 2.1 core API and the JDBC 2.0
optional package API and although these TWO APIs have been combined into one in
version 3.0

The JDBC classes and interfaces remain in two packages:


• java.sql
• javax.sql;

The javax.sql package also introduces container managed connection pooling,


distributed transaction and xxxxxx.

JDBC DRVERS

• TYPE-I DRIVER (JDBC-ODBC BRIDGE DRIVER)

• TYPE-II DRIVER (PART JAVA PART NATIVE DRIVER)

Prepared by: Praveen Kumar Mishra 2

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


• TYPE-III DRIVER (NET PROTOCOL DRIVER)

• TYPE-IV DRIVER (PURE JAVA DRIVER)

Type-I Driver JDBC-ODBC Bridge Driver

Open Database Connectivity (ODBC) was originally created to provide an API


standard for SQL on Microsoft window platform and was later enhanced to provide
SDKs for other platforms. ODBC is partially based on X/Open call level interface (CLI)
specifications which is an standard API for database access. This API provides
binding in the C and COBOL language for database access. CLIs intended to be
platform and database neutral.

TYPE-II DRIVER (PART JAVA PART NATIVE DRIVER)

TYPE-III DRIVER (NET PROTOCOL DRIVER)

Type-IV Driver JDBC-ODBC Bridge Driver

• Translates JDBC calls() directly to dB protocol


• Always provided by vendor
• Most efficient, because JDBC calls directly translated into database protocol.
• This driver is like a connector.
• Oracle driver is found in /oracle/ora92/jdbc/lib/classes12.jar or classes12.zip

Prepared by: Praveen Kumar Mishra 3

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


JDBC DATA TYPES

JDBC Type Java Type


BIT Boolean
TINYINT Byte
S MALLINT Short
INTEGER Int
BIGINT Long
REAL Float
FLOAT Double
DOUBLE
BINARY byte[]
VARBINARY
LONGV ARB INARY
CHAR String
VARCHAR
LONGVARCHAR

JDBC Type Java Type


NUMERIC BigDecimal
DECIMAL
DATE java.sql. Date
TIME java.sql.1imestamp
TIMESTAMP
CLOB Clob*
BLOB Blob*
ARRAY Array*
DISTINCT mapping of underlying type
STRUCT Struct*
REF Rer
JAVA OBJECT underlying Java class

Prepared by: Praveen Kumar Mishra 4

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


METADATA

The JDBC API also includes facilities to obtain metadata about the database,
parameters to statements, and results:

Sr. Class Desciption

1. Java.sql.DatabaseMetadata You can find out about database features using


this interface. You can obtain an instance of
this interface using the java.sql.Connection.

2. Java.sql.ResultSetMetaData This interface provides methods to access


metadata of the ResultSet, such as the names
of columns, their types, the corresponding
table name and other properties.

3. Java.sql.ParameterMetadata This interface allows you to access the


database types of parameters in prepared
statements.

1. DatabaseMetadata

DatabaseMetadata: Example

Connection connection = DriverManager.getConnection(url);


// II Look up info about the database as a whole
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName= dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion = dbMetaData.getDatabaseProductVersion();

Prepared by: Praveen Kumar Mishra 5

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


Interfaces of java.sql package:

• Driver
• Connection
• Statement
• PreparedStatement
• CallableStatement
• ResultSet
• ResultSetMetaData
• DatabaseMetaData

Importance of java.sql package

• It tests the functionality of a JDBC Driver


• It ensures that all classes and methods defined in the JDBC API are
implemented

Exceptions defined by java.sql package:

• DataTruncation
• SQLException
• SQLWarning

SEVEN BASIC STEPS IN USING JDBC

I. Import java.sql.* package

II. Load (Register) the driver

III. Establish the Connection

IV. Create a Statement object

V. Execute a query

VI. Process the results

VII. Close the connection

Prepared by: Praveen Kumar Mishra 6

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


I. Import java.sql.* package

Write the following import statement before class definition :

import java.sql.*;

II. Load (Register) the driver

The DriverManager requires each driver needed by the application must be


registered before use, so that the DriverManager is aware of it.

There are several ways to register the JDBC driver

a. Using Class.forName()

b. Using DriverManager.registerDriver()

c. Using System.setProperty();

a. Using Class.forName()

Format – Class.forName (“Fully Qualified Class Name of Main Driver Class”);

When we load the driver class (using the Class.forName ()), the registration
happens automatically

b. Using DriverManager.registerDriver()

Format – DriverManager.registerDriver (new FullyQualifiedClassName ())

In JDBC each driver provider is required to register an instance of the driver


with the java.sql.DriverManager class during the static initialization. The
java.sql.DriverManager is a static class & it has following method:

c. Using System.setProperty()

Alternatively, we can specify a list of drivers using the Java properties


mechanism. For example, the following snippet would allow the
java.sql.DriverManager class to load a list of drivers when an attempt is

Prepared by: Praveen Kumar Mishra 7

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


made to establish a connection:

Format – System.setProperty (“jdbc.drivers”, “FullyQualifiedClassName”)

Note: you can specify multiple drivers as a list separated by colons (:)

Later, we shall discuss the javax.sql.DataSource interface that provides a better


alternative to java.sql.DriverManager for J2EE applications.

String driver = “oracle.jdbc.driver.OracleDriver ";

String driver = "com.mysql.jdbc.Driver";

try

Class.forName (driver);

catch(ClassNotFoundException cnfe)

System.out.println ("Error loading driver: " cnfe);

Q. Difference between Class.forName() & DriverManager.registerDriver()

Answer -------

Prepared by: Praveen Kumar Mishra 8

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


III. Establish the Connection

To communicate with a database using JDBC, we must first establish a


connection to the database through appropriate JDBC driver.

The DriverManager has three variants of a static method getConnection () used


to establish connections. The DriverManager delegates these calls to the
connect() method on the java.sql.Driver interface.

Different methods for getting a connection:

• public static Connection getConnection(String url) throws SQLException

• public static Connection getConnection(String url, java.util.Properties info)


throws SQLException

• public static Connection getConnection(String url, String user, String


password) throws SQLException

JDBC URL

It has following format:

protocol:<sub-protocol>:<subName>

Note: jdbc is the only allowed protocol.

Ex:

String mysqlURL =

“protocol:sub-protocol://machine-name:port/dBName?user=;password=”;

or “Jdbc:mysql://localhost:3306/myDataBase?user=;password=”;

String oracleURL =

“protocol:sub-protocol:driver-type:@machine-name:port:dBName”;

Or “jdbc:oracle:thin:@90.103.5.1:1521:AHIS”; // example of thin driver

String oracleURL = "jdbc:oracle:oci8:@AHIS"; // example of oci driver

Prepared by: Praveen Kumar Mishra 9

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


Format -> Connection con = DriverManager.getConnection (oracleURL,
username, password);

Optionally, look up information about the database


DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion =dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion) ;

IV. Create a Statement object

We can use a Connection object to create a Statement.

There are three types of statement according to the type of SQL query to be fired

a. Statement

b. PreparedStatement

c. CallableStatement

a. Statement
Statement statement = connection.createStatement();
Statement statement = connection.createStatement(int ResultSetType, int
resultSetConcurrency);

We use createStatement () method for data fetching / selection. Our sql


query is of type select.

Ex: select * from table name.

The resultSetType & resultSetConcurrency arguments apply to ResultSet


object created by executing query.

The first argument specifies the required ResultSet type. We will see it later.

Prepared by: Praveen Kumar Mishra 10

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


The second argument specifies if ResultSet is read-only.

b. PreparedStatement

String query = “insert into tableName(fieldName1, fieldName2) values(?,?)”

PreparedStatement pst=connection.prepareStatement(String query);

// ? are parameters, that has to be set.

We use prepareStatement() method for updating the record (insert, delete,


update)

Note: Before we go in details, better we understand how a query returns


the result, when fired to the oracle database (yes, this is for Oracle only).

Every time, we fire a query to Oracle database, there are three steps taken
by Oracle database server:

Parsing: The query is checked weather its format is OK or not.

Compilation: The parsed query is now compiled.

Execution: The compiled query is now executed & the result is returned.

Note: While creating the PreparedStatement object, we pass the query.

PreparedStatement are pre-parsed & precompiled statement. So the first


two steps are not needed. Only execution is required. That is why
PreparedStatement are fast compared to Statement.

c. CallableStatement

String query = “{? = procedureName(?,?)}”;

CallableStatement cst = connection.prepareCall (String query);

We use prepareCall () method when the sql query is to execute PL/SQL


block (for example stored procedure)

Prepared by: Praveen Kumar Mishra 11

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


V. Execute a query

Depending on the type of statement (or query) execution of query is of three


types:

a. executeQuery()

String query = “select * from tableName where uname=’”+username +”’ ”;

ResultSet rs = statement.executeQuery(query);

b. executeUpdate()

pst.setInt(int index, int data1); // ex: pst.setInt(1, 55);

pst.setString(int index, String data2); // ex: pst.setString(2, “prav”);

int recordsUpdated = pst.executeUpdate();

c. Execute()

con.execute();

Note: we will see an example using CallableStatement.

Use setQueryTimeout to specify a maximum delay to wait for results

VI. Process the results

Depending on the type of statement (or query) there are three types of result:

a. ResultSet

When a query of select type is fired, the return type of executeQuery() is an


object of ResultSet.

Using the next() method on the ResultSet object we can get a pointer
pointing to each record. Now calling getString() or getInt() method on
ResultSet object, we can get the date from a specific column.

Prepared by: Praveen Kumar Mishra 12

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


Note: Later, we will see ResultSet in depth.

b. int

When a query of update type is fired, the return type of executeUpdate() is


integer, which tells number of records updated.

c. *****

VII. Close the connection

As opening a connection is expensive, postpone this step If additional database


operations are expected.

We must close every object (ResultSet, Statement, Connection) we open (or


created) in the reverse order, so that the unused resources can be freed.

rs.close(); // resultset closed

st.close(); // statement closed

con.closed(); // connection closed

Examples showing connection of java program to database using JDBC


drivers.

a. Using JDBC Type-I Driver

b. Using JDBC Type-IV Driver

Prepared by: Praveen Kumar Mishra 13

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


RESULSET

A ResultSet contains the results of the SQL query, represented by a table with rows
and columns.

ResultSet is a cursor (pointer) which points to table returned by query fired to dB.

Initially the cursor (returned by query) points to Before First Record. We now need
to point it to first record to get data from that record.

When next () method is called first time on the ResultSet object, it points to first
record. The next () method returns Boolean value, true if there is a record, false
otherwise.

Prepared by: Praveen Kumar Mishra 14

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


The ResultSet reference variable or object has a number of methods, to get the
required information from the table returned by firing query.

All methods can throw a SQLException

Sr. Method Description

1. Close() • Releases the JDBC and database resources

• The result set is automatically closed when the


associated Statement object executes a new
query

2. getMetaDataObject()
• Returns a ResultSetMetaData object
containing information about the columns in
the ResultSet

Prepared by: Praveen Kumar Mishra 15

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


3. Next()
• Attempts to move to the next row in the
ResultSet

• If successful true is returned; otherwise,


fa1se.

• The first call to next positions the cursor at the


first row.

4. getWarnings()
• Returns the first SQLWarning or null, if no
warnings occurred

5. findColumn()
• Corresponding to the specified column name

6. previous() Attempts to move to the next row in the ResultSet

7. getInt()

8. getString()

9. getDouble()

10. getLong()

11. getTime()

12.

13.

14.

15.

Prepared by: Praveen Kumar Mishra 16

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


All these methods require either the column name (as a String) or the column
index as the argument. The syntax of two variants of getString() methods is
shown below:

public String getString(int columnIndex) throws SQLException

public String getString(String columnName) throws SQLException

Note: In cases where the column index is subjected to change due to changes in
SQL or the database schema, it is preferable to use column names in these
methods.

Properties of ResultSet:

ResultSet

Scrollability Concurrency

NonScrollable Scrollable Read Only Updatable

Insensitive Scrolling

Sensitive Scrolling

1. Scrollability:

1.1 Non-Scrollable: Forward only. Default.

1.2 Scrollable:

Prepared by: Praveen Kumar Mishra 17

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


1.2.1 Sensitive Scrolling: Senses the parallel transaction, if data in
resultset is modified by parallel transaction, it is reflected in resultset.

1.2.2 Insensitive Scrolling: Doesn’t sense the parallel transaction.

2. Concurrency:

2.1 Read-Only:

o Default.

o Can be any, either sensitive or insensitive.

2.2 Updatable:

o Data is read & could be written in same ResultSet.

o Can be any, either sensitive or insensitive.

o JDBC 2.0 onwards.

Above properties can be set in the createStatement ();

3 ResultSetMetaData Interface

Prepared by: Praveen Kumar Mishra 18

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


The ResultSet interface also allows us to find out the structure of the ResultSet.
The getMetaData() method helps us to retrieve a java.sql.ResultSetMetaData
object that has several method to describe resultset cursors.

ResultSetMetaData answers the following questions:

• How many columns are in the result set


• What is the name of a given column
• Are the column names case sensitive
• What is the data type of a specific column
• What is the maximum character size of a column
• Can you search on a given column

Useful MetaData Methods


Sr. Methods Description

1. getCatalogName()

2. getColumnCount() Returns the number of columns in the result set

3. getTableName()

4. getSchemaName()

5. getColumnCount()

6. getColumnName() returns the database name of the column

7. getColumnLabel() returns the suggested column label for printouts

8. getColumnType() Returns the SQL type for the column to compare


against types in java.sql.Types

9. getColumnTypeName()

10. getColumnClassName()

11. getColumnDisplaySize() Returns the maximum width of the specified


column in character

12. isWritable() This method indicates whether it is possible for a


write to succeed

13. getScale()

14. getPrecision()

15. isNullable() Indicates whether storing a NULL in the column is

Prepared by: Praveen Kumar Mishra 19

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


legal

16. isCurrency()

17. isSearchable() Returns true or false if the column can be used in a


WHERE clause

18. isCaseSensitive()

19. isSigned()

20. isAutoIncrement()

21. isReadOnly() This method indicates if the column is definitely


not writable

Note: For more methods refer java documentation from sun.

ResultSetMetaData Example:
Statement st = con.createStatement();
String query = “select * from tableName”;
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmetadata = rs.getMetaData();
Int noColumns = rsmetadata.getColumnCount();
// Column numbers start from 1
for(int i=1; i<noColumns +1; i++)
{
SOP(rsmetadata.getColumnName(i) + “--” + rsmetadata.getColumnType(i));
}

USING DIFFERENT STATEMENTS

HANDLING SQL EXCEPTIONS

SUBMITTING MULTIPLE TSTATEMENT AS A SINGLE TRANSACTION

Prepared by: Praveen Kumar Mishra 20

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


JDBC DATA TYPES

Oracle provides three categories of JDBC drivers:

• JDBC Thin Driver (No local Net8 installation required/ handy for applets)
• JDBC OCI for writing stand-alone Java applications
• JDBC KPRB driver (default connection) for Java Stored Procedures and
Database JSP's.

Oracle's JDBC Thin driver uses Java sockets to connect directly to Oracle. It provides
its own TCP/IP version of Oracle's Net8 (SQL*Net) protocol. Because it is 100% Java,
this driver is platform independent and can also run from a Web Browser (applets).

Oracle's JDBC OCI drivers use Oracle OCI (Oracle Call Interface) to interact with an
Oracle database. You must use a JDBC OCI driver appropriate to your Oracle client
installation. The OCI driver works through either SQL*Net or Net8.

• JDBC OCI7 works with an Oracle7 client.


• JDBC OCI8 works with an Oracle8 client.

Either of these client versions can access Oracle7 or Oracle8 servers.

The JDBC OCI drivers allow you to call the OCI directly from Java, thereby providing
a high degree of compatibility with a specific Version of Oracle. Because they use
native methods, they are platform specific.

Oracle's JDBC KBPR driver is mainly used for writing Java stored procedures, triggers
and database JSPs. It uses the default/ current database session and thus requires
no additional database username, password or URL.

All three drivers support the same syntax and API's. Oracle needs three drivers to
support different deployment options. Looking at source code, they will only differ in

Prepared by: Praveen Kumar Mishra 21

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


the way you connect to the database. Remember, you must use a JDBC version that
matches the version of your Java Development Kit.

• Back to top of file

Ø How does one connect with the JDBC Thin Driver?

The the JDBC thin driver provides the only way to access Oracle from the Web
(applets). It is smaller and faster than the OCI drivers, and doesn't require a
pre-installed version of the JDBC drivers.

import java.sql.*;

class dbAccess {

public static void main (String args []) throws SQLException

DriverManager.registerDriver (new oracle.jdbc.driver.OracleDri ver());

Connection conn = DriverManager.getConnection

("jdbc:oracle:thin:@hostname:1526:orcl", "scott", "tiger");

// @machineName:port:SID, userid, password

Statement stmt = conn.createStatemen t();

ResultSet rset = stmt.executeQuery("select BANNER from


SYS.V_$VERSION");

while (rset.next())

System.out.println (rset.getString(1)); // Print col 1

stmt.close();

• Back to top of file

How does one connect with the JDBC OCI Driver?

Prepared by: Praveen Kumar Mishra 22

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


One must have Net8 (SQL*Net) installed and working before attempting to use one
of the OCI drivers.

import java.sql.*;

class dbAccess {

public static void main (String args []) throws SQLException

try {

Class.forName ("oracle.jdbc.driver.OracleDriver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

Connection conn = DriverManager.getCo nnection

("jdbc:oracle:oci8:@hostname_orcl", "scott", "tiger");

// or oci7 @TNSNames_Entry, userid, password

Statement stmt = conn.createStatement();

ResultSet rset = stmt.executeQuery("select BANNER f rom


SYS.V_$VERSION");

while (rset.next())

System.out.println (rset.getString(1)); // Print col 1

stmt.close();

• Back to top of file

Prepared by: Praveen Kumar Mishra 23

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


Ø What is the query used to display all tables names in SQL Server (Query
analyzer)?
select * from information_schema.tables

Ø What is the fastest type of JDBC driver?

JDBC driver performance will depend on a number of issues:

• the quality of the driver code,

• the size of the driver code,

• the database server and its load,

• network topology,

• the number of times your request is translated to a different API.

In general, all things being equal, you can assume that the more your request
and response change hands, the slower it will be. This means that Type 1 and
Type 3 drivers will be slower than Type 2 drivers (the database calls are make
at least three translations versus two), and Type 4 drivers are the fastest
(only one translation).

Ø What Class.forName will do while loading drivers.

It is used to create an instance of a driver and register it with the


DriverManager. When you have loaded a driver, it is available for making a
connection with a DBMS.

Ø How to Retrieve Warnings.

SQLWarning objects are a subclass of SQLException that deal with database


access warnings. Warnings do not stop the execution of an application, as
exceptions do; they simply alert the user that something did not happen as
planned. A warning can be reported on a Connection object, a Statement object
(including PreparedStatement and CallableStatement objects), or a ResultSet
object. Each of these classes has a getWarnings method, which you must invoke
in order to see the first warning reported on the calling object.

SQLWarning warning = stmt.getWarnings();

Prepared by: Praveen Kumar Mishra 24

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


if (warning != null)
{
while (warning != null)
{
System.out.println("Message: " +
warning.getMessage());
System.out.println("SQLState: " +
warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

Ø What are stored procedures? How is it useful?


A stored procedure is a set of statements/commands which reside in the
database. The stored procedure is precompiled and saves the database the effort
of parsing and compiling sql statements everytime a query is run.

Each Database has it’s own stored procedure language, usually a variant of C
with a SQL preproceesor. Newer versions of db’s support writing stored
procedures in Java and Perl too.

Before the advent of 3-tier/n-tier architecture it was pretty common for stored
procs to implement the business logic( A lot of systems still do it). The biggest
advantage is of course speed. Also certain kind of data manipulations are not
achieved in SQL. Stored procs provide a mechanism to do these manipulations.

Stored procs are also useful when you want to do Batch


updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC
Connection may be significant in these cases.

Ø
Ø D
Ø Dd

Prepared by: Praveen Kumar Mishra 25

PDF created with FinePrint pdfFactory trial version www.pdffactory.com


Prepared by: Praveen Kumar Mishra 26

PDF created with FinePrint pdfFactory trial version www.pdffactory.com

También podría gustarte