Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
To retrieve this image and create a byte array that can be passed to
createImage, do the following:
int itemnumber=400456;
byte[] imageBytes;
reg.balance = balance;
ByteArrayOutputStream regStore =
new ByteArrayOutputStream();
ObjectOutputStream regObjectStream =
new ObjectOutputStream(regStore);
regObjectStream.writeObject(reg);
byte[] regBytes=regStore.toByteArray();
regObjectStream.close();
regStore.close();
ByteArrayInputStream regArrayStream =
new ByteArrayInputStream(regBytes);
ps=con.prepareStatement(
"insert into registration (
theuser, theclass) values (?, ?)");
ps.setString(1, theuser);
ps.setBinaryStream(2, regArrayStream,
regBytes.length);
}
}
}
}
if (ps.executeUpdate() != 1) {
throw new CreateException ();
}
RegistrationPK primaryKey =
new RegistrationPKImpl();
primaryKey.theuser(theuser);
return primaryKey;
catch (IOException ioe) {
throw new CreateException ();
catch (CreateException ce) {
throw ce;
catch (SQLException sqe) {
System.out.println("sqe="+sqe);
throw new CreateException ();
finally {
try {
ps.close();
con.close();
} catch (Exception ignore) {
}
if (pk == null) {
throw new FinderException ();
}
Connection con = null;
PreparedStatement ps = null;
try {
con=getConnection();
ps=con.prepareStatement("
select theclass from
registration where theuser = ?");
ps.setString(1, pk.theuser());
ps.executeQuery();
ResultSet rs = ps.getResultSet();
if(rs.next()){
byte[] regBytes = rs.getBytes(1);
ByteArrayInputStream regArrayStream =
new ByteArrayInputStream(regBytes);
ObjectInputStream regObjectStream =
new ObjectInputStream(
regArrayStream);
RegistrationImpl reg=
(RegistrationImpl)
regObjectStream.readObject();
return reg;
}
else {
throw new FinderException ();
}
} catch (Exception sqe) {
System.out.println("exception "+sqe);
throw new FinderException ();
}
finally {
try {
rs.close();
ps.close();
con.close();
}
catch (Exception ignore) {}
}
}
BLOBs and CLOBs: Storing large fields in a table with the other data
is not necessarily the optimum place especially if the data has a
variable size. One way to handle large, variable sized objects is with
the Large Objects (LOBs) type. LOBs use a locator, essentially a
pointer, in the database record that points to the real database field.
There are two types of LOBs: Binary Large Objects (BLOBs) and
Character Large Objects (CLOBs). When you access a BLOB or CLOB,
the data is not copied to the client. To retrieve the actual data from a
result set, you have to retrieve the pointer with a call to BLOB
Controlling Transactions
By default, JDBC statements are processed in full auto-commit mode.
This mode works well for a single database query, but if an operation
depends on several database statements that all have to complete
successfully or the entire operation is cancelled, a finer transaction is
needed.
A description of transaction isolation levels is covered in more detail in
Chapter 3: Data and Transaction Management. To use transaction
management in the JDBC platform, you first need to disable the full
auto-commit mode by calling:
Connection con= getConnection();
con.setAutoCommit(false);
At this point, you can either commit any following JDBC statements or
undo any updates by calling the Connection.rollback method. The
rollback call is commonly placed in the Exception handler, although it
can be placed anywhere in the transaction flow.
This next example inserts an auction item and decrements the user's
balance. If the balance is less than zero, the entire transaction is rolled
back and the auction item is removed.
public int insertItem(String seller,
String password,
String description,
int auctiondays,
double startprice,
String summary) {
Connection con = null;
int count=0;
double balance=0;
java.sql.Date enddate, startdate;
Statement stmt=null;
PreparedStatement ps = null;
try {
con=getConnection();
con.setAutoCommit(false);
stmt= con.createStatement();
stmt.executeQuery(
"select counter from auctionitems");
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
count=rs.getInt(1);
}
Calendar currenttime=Calendar.getInstance();
java.util.Date currentdate=currenttime.getTime();
startdate=new java.sql.Date(
currentdate.getTime());
currenttime.add(Calendar.DATE, auctiondays);
enddate=new java.sql.Date((
currenttime.getTime()).getTime());
ps=con.prepareStatement(
"insert into auctionitems(
id, description, startdate, enddate,
startprice, summary)
values (?,?,?,?,?,?)");
ps.setInt(1, count);
ps.setString(2, description);
ps.setDate(3, startdate);
ps.setDate(4, enddate);
ps.setDouble(5, startprice);
ps.setString(6, summary);
ps.executeUpdate();
ps.close();
ps=con.prepareStatement(
"update registration
set balance=balance -0.50
where theuser= ?");
ps.setString(1, seller);
ps.close();
stmt= con.createStatement();
stmt.executeQuery(
"select balance from registration
where theuser='"+seller+"'");
rs = stmt.getResultSet();
if(rs.next()) {
balance=rs.getDouble(1);
}
stmt.close();
if(balance <0) {
con.rollback();
con.close();
return (-1);
}
stmt= con.createStatement();
stmt.executeUpdate(
"update auctionitems set
counter=counter+1");
stmt.close();
con.commit();
con.close();
return(0);
} catch(SQLException e) {
try {
con.rollback();
con.close();
stmt.close();
ps.close();
}catch (Exception ignore){}
}
return (0);
}
Escaping Characters
The JDBC API provides the escape keyword so you can specify the
character you want to use to escape characters. For example, if you
want to use the percent sign (%) as the percent sign and not have it
interpreted as the SQL wildcard used in SQL LIKE queries, you have to
escape it with the escape character you specify with the escape
keyword.
This next statements shows how you would use the escape keyword to
look for the value 10%.
stmt.executeQuery(
"select tax from sales where tax like
'10\%' {escape '\'}");
Make sure your database is started with large java_pool_size (>20M) and shared_pool_size
(>50M) INIT.ORA parameter values.
Run the $ORACLE_HOME/javavm/install/initjvm.sql script from SYS AS SYSDBA to install the
Oracle JServer Option on a database.
Grant JAVAUSERPRIV to users that wants to use Java:
SQL> GRANT JAVAUSERPRIV TO SCOTT;
The rmjvm.sql script can be used to deinstall the JServer option from your database.
Follow the steps in the Oracle Migrations Guide to upgrade or downgrade the JServer option from one
release to another.
Back to top of file
How does one load Java Source code into the database?
Use the "CREATE OR REPLACE JAVA SOURCE" command or "loadjava" utility. See this script for an
example.
Loaded code can be viewed by selecting from the USER_SOURCE view.
Back to top of file
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 uses 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.
System.out.println (rset.getString(1));
stmt.close();
// Print col 1
}
}
Back to top of file
}
Back to top of file
JDeveloper is the Oracle IDE (Integrated Development Environment) for developing SQLJ and JDBC
programs, applets, stored procedures, EJB's, JSP's etc.
JDeveloper are extremely resource hungry and requires a big workstation. However, it provides an
extremely productive environment for Java Developers.
Back to top of file
SQL*Plus: drop java class .../ drop package ... (drop the wrapper)
dropjava utility: dropjava -u scott/tiger myPackage.myClass
import java.sql.*;
public class CreateCoffees {
public static void main(String args[]) {
String url = "jdbc:mySubprotocol:myDataSource";
Connection con;
String createString;
createString = "create table COFFEES " +
"(COF_NAME VARCHAR(32), " +
"SUP_ID INTEGER, " +
"PRICE FLOAT, " +
"SALES INTEGER, " +
"TOTAL INTEGER)";
Statement stmt;
try {
Class.forName("myDriver.ClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "myLogin", "myPassword");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
=============================================