Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
464
Chapter 18 JDBC and Database Connection Pooling
JDBC is most often used from servlets or regular desktop applications but
is also sometimes employed from applets. If you use JDBC from an applet,
remember that, to prevent hostile applets from browsing behind corporate
firewalls, browsers prevent applets from making network connections any 
where except to the server from which they were loaded. Consequently, to
use JDBC from applets, either the database server needs to reside on the
same machine as the HTTP server or you need to use a proxy server that
reroutes database requests to the actual server.
Establish the Connection
To make the actual network connection, pass the URL, the database user 
name, and the password to the 
getConnection
 method of the 
Driver 
Manager
 class, as illustrated in the following example. Note that
getConnection
 throws an 
SQLException
, so you need to use a 
try
/
catch
block. I'm omitting this block from the following example since the methods
in the following steps throw the same exception, and thus you typically use a
single 
try
/
catch
 block for all of them.
String username = "jay_debesee";
String password = "secret";
Connection connection =
DriverManager.getConnection(oracleURL, username, password);
An optional part of this step is to look up information about the database
by using the 
getMetaData
 method of 
Connection
. This method returns a
DatabaseMetaData
 object which has methods to let you discover the name
and version of the database itself (
getDatabaseProductName
, 
getData 
baseProductVersion
) or of the JDBC driver (
getDriverName
, 
get 
DriverVersion
). Here is an example:
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName = 
dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion = 
dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion);
Other useful methods in the 
Connection
 class include 
prepareState 
ment
 (create a 
PreparedStatement
; discussed in Section 18.6), 
prepare 
Call
 (create a 
CallableStatement
), 
rollback
 (undo statements since last
commit
), 
commit
 (finalize operations since last 
commit
), 
close
 (terminate
connection), and 
isClosed
 (has the connection either timed out or been
explicitly closed?).
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved