Вы находитесь на странице: 1из 9

JDBC

Java Database Connectivity in short called as JDBC. It is a java API which enables the java
programs to execute SQL statements. JDBC has been developed under the Java Community
Process that allows multiple implementations to exist and be used by the same application.
JDBC provides methods for querying and updating the data in Relational Database
Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading
the correct Java packages and drivers and registering them with the JDBC Driver Manager
that is used as a connection factory for creating JDBC connections which supports creating
and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is
the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that
Java is platform independent, so JDBC makes it possible to write a single database
application that can run on different platforms and interact with different Database
Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used
for accessing and managing database, but the difference is that JDBC is designed specifically
for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to
your query.
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver.
ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental
use or when no other alternative is available.

Type 1: JDBC-ODBC Bridge

Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC
drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then
to the database, and this applies even in the reverse process. They are the slowest of all driver
types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver
Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls
into database-specific calls i.e. this driver is specific to a particular database. Some distinctive
characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native
api.

Type 2: Native api/ Partly Java Driver


Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than
that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be
used for the Internet.
2. Like Type 1 drivers, its not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a
database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver


All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The middletier then translates the request to the database. If the middle-tier server can in turn use Type1,
Type 2 or Type 4 drivers.

Type 3: All Java/ Net-Protocol Driver

Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present on
client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query
results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take
longer, since the data comes through the backend server.

Type 4 JDBC Driver


Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server.

Type 4: Native-protocol/all-Java driver

Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to
achieve platform independence and eliminate deployment administration issues. It is most
suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate
database requests to ODBC or a native connectivity interface or to pass the request on to another
server, performance is typically quite good.
3. You dont need to install special software on the client or server. Further, these drivers can be
downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.

Key Terminology
DatabaseThe whole point of JDBC is to provide a uniform connection between Java code
and a database. The database might be anything from Microsoft Access to IBMs DB2.
DriverThe driver is the core component for JDBC. Drivers are written by vendors and must
support the basic features of the JDBC specification.
ConnectionA Connection is a Java interface defining a link to a database. The Connection is
essentially a pipeline between your code and the database.
StatementA Statement is a Java interface that represents messages sent from your code to the
database. These statements can use database-specific SQL or a form of SQL-92 that is
compatible across all database systems.
ResultSetA ResultSet is a Java interface representing a set of data drawn from the database.
The DriverManager : is a container for all the registered drivers and a superfactory for
Connection objects generated by the different drivers.
Statement
Void addBatch(String sql)
Adds the given SQL command to the current list of commmands for this Statement object.

int[]executeBatch()
Submits a batch of commands to the database for execution and if all commands execute
successfully, returns an array of update counts.
void close()
Releases this Statement object's database and JDBC resources immediately instead of waiting
for this to happen when it is automatically closed.
ResultSet executeQuery(String sql)
Executes the given SQL statement, which returns a single ResultSet object.
Int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL
INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a
DDL statement.
PreparedStatement

CallableStatement
CallableStatement cstmt = con.prepareCall(
"{call getTestData(?, ?)}");
IN Parameters
Passing in any IN parameter values to a CallableStatement object is done using the setXXX
methods inherited from PreparedStatement. The type of the value being passed in determines
which setXXX method to use (setFloat to pass in a float value, setBoolean to pass in a
boolean, and so on). Of the programs that use parameters, the vast majority use only IN
parameters.

Making Batch Updates


CallableStatement cstmt = con.prepareCall(
"{call updatePrices(?, ?)}");
cstmt.setString(1, "Colombian");
cstmt.setFloat(2, 8.49f);
cstmt.addBatch();
cstmt.setString(1, "Colombian_Decaf");
cstmt.setFloat(2, 9.49f);
cstmt.addBatch();

int [] updateCounts = cstmt.executeBatch();

OUT Parameters
CallableStatement cstmt = con.prepareCall(
"{call getTestData(?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 3);
ResultSet rs = cstmt.executeQuery();
// . . . retrieve result set values with rs.getXXX methods
byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2);

ResultSet
next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned after the last row.
previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on
a row and false if the cursor is positioned before the first row.
first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now
positioned on the first row and false if the ResultSet object does not contain any rows.
last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet object does not contain any rows.
beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the
ResultSet object does not contain any rows, this method has no effect.
afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the
ResultSet object does not contain any rows, this method has no effect.

By Comun Name
Using the getXXX Methods

The ResultSet interface declares getter methods (getBoolean, getLong, and so on) for
retrieving column values from the current row.
ResultSet srs = stmt.executeQuery(
"SELECT COF_NAME, PRICE FROM COFFEES");
while (srs.next()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
By Comun Index
String s = srs.getString(1);
float n = srs.getFloat(2);
List of Driver urls
1. Oracle JDBC ThinDriver
jdbc:oracle:thin:@hostname:port:database.
The default Oracle port is 1521.
2. Oracles Type 2 driver (uses Oracles TNSNames entry)
jdbc:oracle:oci8:@SQLNETinstanceName
(e.g., jdbc:oracle:oci8:@CodeNotes)
3. JDBC-ODBC bridge (uses an ODBC datasource you must establish on your machine)
jdbc:odbc:datasource;param=value;
(e.g., jdbc:odbc:CodeNotes;uid=sa;pwd=snuffelupugus)
4. Sybase
jdbc:sybase:Tds:ipaddress:port:database.
The default port is 4100.

Вам также может понравиться