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

Java Database Connectivity

JDBC is a Java API for executing SQL statements.


It consists of a set of classes and interfaces written in the Java
programming language.
JDBC provides a standard API for tool/database developers and
makes it possible to write database applications using a pure Java
API.

What Does JDBC Do?


JDBC makes it possible to do three things:
establish a connection with a database
send SQL statements
process the results.
JDBC Driver Types
1.JDBC-ODBC bridge plus ODBC driver: The bridge product
provides JDBC access via ODBC drivers.
2.Native-API partly-Java driver: This kind of driver converts
JDBC calls into calls on the client API for Oracle, Sybase,
Informix, DB2, or other DBMS.
3.JDBC-Net pure Java driver: This driver translates JDBC calls
into a DBMS- independent net protocol which is then translated
to a DBMS protocol by a server.
4.Native-protocol pure Java driver: This kind of driver converts
JDBC calls into the network protocol used by DBMS directly. This
allows a direct call from the client machine to the DBMS server.
Since many of these protocols are proprietary, the database
vendors themselves will be the primary source.
The JDBC-ODBC bridge allows ODBC drivers to be used as JDBC
drivers
Load the driver
try {
Class.forName("oracle.jdbc.OracleDriver");
}
catch { ClassNotFoundException cnfe) { }

Define the Connection URL

String host = 127.0.0.1";

String dbName = ORCL";

int port = 1521;

String oracleURL = "jdbc:oracle:thin:@" + host +


":" + port + ":" + dbName;
Establish the Connection
String username = SCOTT";
String password = TIGER";
Connection connection =
DriverManager.getConnection(oracleURL,
username, password);

Optionally, look up information about the database


DatabaseMetaData dbMetaData =
connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
String productVersion =
dbMetaData.getDatabaseProductVersion();
Create a Statement
Statement statement = connection.createStatement();

Execute a Query
String query = "SELECT col1, col2, col3 FROM sometable";

ResultSet resultSet = statement.executeQuery(query);

To modify the database, use executeUpdate, supplying a


string that uses UPDATE, INSERT, or DELETE
Use setQueryTimeout to specify a maximum delay to wait for
results.
Process the Result
while(resultSet.next())
{
System.out.println(resultSet.getString(1) + " " +
resultSet.getString(2) +
" " +
resultSet.getString(3));
}
First column has index 1, not 0
ResultSet provides various getXxx methods that take a column
index or column name and returns the data
You can also access result meta data (column names, etc.)
Close the Connection
connection.close();
PreparedStatement
The PreparedStatement interface inherits from Statement and
differs from it in two ways:
1. Instances of PreparedStatement contain an SQL statement
that has already been compiled. This is what makes a
statement "prepared."
2. The SQL statement contained in a PreparedStatement object
may have one or more IN parameters.
An IN parameter is a parameter whose value is not
specified when the SQL statement is created.
Instead the statement has a question mark ("?") as a
placeholder for each IN parameter.
A value for each question mark must be supplied by the
appropriate setXXX method before the statement is executed.
Because PreparedStatement objects are precompiled, their
execution can be faster than that of Statement objects.
Creating PreparedStatement Objects
PreparedStatement ps=
con.prepareStatement( update tab1 set m = ? Where x = ?");
The object ps now contains the statement which has already been
sent to the DBMS and been prepared for execution.
Passing IN Parameters
Before a PreparedStatement object is executed, the value of each
? parameter must be set.
This is done by calling a setXXX method, where XXX is the
appropriate type for the parameter.
ps.setLong(1, 123456789);
ps.setLong(2, 100000000);
The following code illustrates setting values for the two parameter
placeholders and executing pstmt 10 times.
In this example, the first parameter is set to "Hi" and remains
constant.
The second parameter is set to a different value each time around
the for loop, starting with 0 and ending with 9.
pstmt.setString(1, "Hi");
for (int i = 0; i < 10; i++)
{
pstmt.setInt(2, i);
int rowCount = pstmt.executeUpdate();
}
Transaction
Once auto-commit mode is disabled, no SQL statements will be
committed until you call the method commit explicitly.
All statements executed after the previous call to the method
commit will be included in the current transaction and will be
committed together as a unit. The following code, in which con is
an active connection, illustrates a transaction:
con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ?
WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement( "UPDATE COFFEES SET TOTAL =
TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();

con.setAutoCommit(true);

calling the method rollback aborts a transaction and returns any


values that were modified to their previous values.
Creating a Stored Procedure
A CallableStatement object provides a way to call stored
procedures in a standard way for all DBMSs.
A stored procedure is stored in a database; the call to the stored
procedure is what a CallableStatement object contains.
The syntax for invoking a stored procedure in JDBC is shown
below.
{call procedure_name(?, ?, ...)}
The syntax for a procedure that returns a result parameter is:
{? = call procedure_name(?, ?, ...)}
The syntax for a stored procedure with no parameters would look
like this:
{call procedure_name}
Creating a CallableStatement Object
CallableStatement objects are created with the Connection
method prepareCall.

CallableStatement cstmt =
con.prepareCall( "{call getTestData(?, ?)}");

Whether the ? placeholders are IN, OUT, or INOUT parameters


depends on the stored procedure getTestData.
IN and OUT 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, and so on).

If the stored procedure returns OUT parameters, the JDBC type of each
OUT parameter must be registered before the CallableStatement
object can be executed.
Registering the JDBC type is done with the method
registerOutParameter.
Then after the statement has been executed, CallableStatement's
getXXX methods retrieve the parameter value.
The correct getXXX method to use is the Java type that corresponds to
The following code registers the OUT parameters, executes the
stored procedure called by cstmt, and then retrieves the values
returned in the OUT parameters.

CallableStatement cstmt =
con.prepareCall( "{call getTestData(?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 3);
cstmt.executeQuery();

byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2, 3);
INOUT Parameters
A parameter that supplies input as well as accepts output (an
INOUT parameter) requires a call to the appropriate setXXX
method in addition to a call to the method registerOutParameter

CallableStatement cstmt =
con.prepareCall( "{call reviseTotal(?)}");
cstmt.setByte(1, 25);
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.executeUpdate();
byte x = cstmt.getByte(1);
Java Type JDBC type
String VARCHAR or LONGVARCHAR
java.math.BigDecimal NUMERIC
boolean BIT
byte TINYINT
short SMALLINT
int INTEGER
long BIGINT
float REAL
double DOUBLE
byte[] VARBINARY or
LONGVARBINARY java.sql.Date DATE
java.sql.Time TIME
New Features in the JDBC 2.0 API

With the JDBC 2.0 API, you will be able to do the following:
Scroll forward and backward in a result set or move to a
specific row
Make updates to database tables using methods in the Java
programming language instead of using SQL commands
Send multiple SQL statements to the database as a unit, or
batch
Moving the Cursor in Scrollable Result Sets
The following line of code illustrates one way to create a scrollable
ResultSet object:
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT * FROM EMP");

The first argument is one of three constants added to the


ResultSet API to indicate the type of a ResultSet object:
TYPE_FORWARD_ONLY , TYPE_SCROLL_INSENSITIVE , and
TYPE_SCROLL_SENSITIVE .
The second argument is one of two ResultSet constants for
specifying whether a result set is read-only or updatable:
CONCUR_READ_ONLY and CONCUR_UPDATABLE .
Specifying the constant TYPE_FORWARD_ONLY creates a result
set, that is, one in which the cursor moves only forward.
If you do not specify any constants for the type and updatability of
a ResultSet object, you will automatically get one that is
TYPE_FORWARD_ONLY and CONCUR_READ_ONLY (as is the
case when you are using only the JDBC 1.0 API).
You will get a scrollable ResultSet object if you specify one of the
following ResultSet constants: TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE .
The difference between the two has to do with whether a result
set reflects changes that are made to it while it is open and
whether certain methods can be called to detect these changes.
Generally speaking, a result set that is
TYPE_SCROLL_INSENSITIVE does not reflect changes made
while it is still open and one that is TYPE_SCROLL_SENSITIVE
does.
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSE
NSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT * FROM
EMP"); srs.afterLast();
while (srs.previous())
{ . }
The following line of code moves the cursor to the fourth
row of srs :
srs.absolute(4);
If srs has 500 rows, the following line of code will move
the cursor to row 497:
srs.absolute(-4);
srs.absolute(4); // cursor is on the fourth row
srs.relative(-3); // cursor is on the first row
srs.relative(2); // cursor is on the third row

The method getRow lets you check the number of the row where
the cursor is positioned.
srs.absolute(4);
int rowNum = srs.getRow(); // rowNum should be 4
Four additional methods let you verify whether the cursor is at a
particular position. The position is stated in their names:
isFirst , isLast , isBeforeFirst , isAfterLast . These
methods all return a boolean.
Making Updates to Updatable Result Sets
Connection con = DriverManager.getConnection();
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT .");
uprs.last();
uprs.updateFloat("PRICE", 10.99);
uprs.updateRow();
Update operations in the JDBC 2.0 API affect column values in the row
where the cursor is positioned, so in the first line the ResultSet uprs
calls the method last to move its cursor to the last row.
The ResultSet. updateXXX methods take two parameters: the
column to update and the new value to put in that column.
Inserting and Deleting Rows Programmatically
Your first step will be to move the cursor to the insert row, which you do
by invoking the method moveToInsertRow .
The next step is to set a value for each column in the row.
You do this by calling the appropriate updateXXX method for each
value.
Finally, you call the method insertRow to insert the row you have just
populated with values into the result set. This one method
simultaneously inserts the row into both the ResultSet object and the
database table from which the result set was selected.
Connection con = DriverManager.getConnection(.");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = stmt.executeQuery("SELECT * FROM


COFFEES");
uprs.moveToInsertRow();
uprs.updateString("COF_NAME", JAVA");
uprs.updateFloat("PRICE", 10.99);
uprs.insertRow();
When you call the method moveToInsertRow , the result set records
which row the cursor is sitting on, which is by definition the current row.
As a consequence, the method moveToCurrentRow can move the
cursor from the insert row back to the row that was previously the
current row.

Note that you can invoke moveToCurrentRow only when the cursor
is on the insert row.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url, "", "");

stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT * FROM EMP");
uprs.absolute(1);
uprs.deleteRow();
uprs.refreshRow();
Making Batch Updates
A batch update is a set of multiple update statements that is submitted to
the database for processing as a batch.
Sending multiple update statements to the database together as a unit
can, in some situations, be much more efficient than sending each update
statement separately.
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO COFFEES" +
"VALUES('Amaretto', 49, 9.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES" +
"VALUES('Hazelnut', 49, 9.99, 0, 0)");
int [] updateCounts = stmt.executeBatch();

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