Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
18.1 Basic Steps in Using JDBC
463
ing a fully qualified class name (i.e., one that includes package names) and
loads the corresponding class. This call could throw a
ClassNotFound
Exception
, so should be inside a
try
/
catch
block. Here is an example:
try {
Class.forName("connect.microsoft.MicrosoftDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.sybase.jdbc.SybDriver");
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
}
One of the beauties of the JDBC approach is that the database server
requires no changes whatsoever. Instead, the JDBC driver (which is on the
client) translates calls written in the Java programming language into the spe
cific format required by the server. This approach means that you have to
obtain a JDBC driver specific to the database you are using; you will need to
check its documentation for the fully qualified class name to use. Most data
base vendors supply free JDBC drivers for their databases, but there are
many third party vendors of drivers for older databases. For an up to date
list, see
http://java.sun.com/products/jdbc/drivers.html
. Many of
these driver vendors supply free trial versions (usually with an expiration date
or with some limitations on the number of simultaneous connections), so it is
easy to learn JDBC without paying for a driver.
In principle, you can use
Class.forName
for any class in your
CLASSPATH
.
In practice, however, most JDBC driver vendors distribute their drivers
inside JAR files. So, be sure to include the path to the JAR file in your
CLASSPATH
setting.
Define the Connection URL
Once you have loaded the JDBC driver, you need to specify the location of
the database server. URLs referring to databases use the
jdbc:
protocol and
have the server host, port, and database name (or reference) embedded
within the URL. The exact format will be defined in the documentation that
comes with the particular driver, but here are two representative examples:
String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host +
":" + port + ":" + dbName;
String sybaseURL = "jdbc:sybase:Tds:" + host +
":" + port + ":" + "?SERVICENAME=" + dbName;
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
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