Database Reference
In-Depth Information
• The class line in the source file indicates a class name.
• The file should have the same name as the class (with a .java extension).
• Compile the .java file to produce a .class file.
Java library files also differ from Java programs in some ways:
• Unlike regular program files, Java library files have no main() function.
• A library file should begin with a package identifier that specifies the position of
the class within the Java namespace.
A common convention for Java package identifiers is to use the domain of the code
author as a prefix; this helps make identifiers unique and avoids conflict with classes
written by other authors. Domain names proceed right to left from more general to
more specific within the domain namespace, whereas the Java class namespace proceeds
left to right from general to specific. Thus, to use a domain as the prefix for a package
name within the Java class namespace, it's necessary to reverse it. For example, my
domain is kitebird.com , so if I write a library file and place it under mcb within my
domain's namespace, the library begins with a package statement like this:
package com . kitebird . mcb ;
Java packages developed for this topic are placed within the com.kitebird.mcb name‐
space to ensure their uniqueness in the package namespace.
The following library file, Cookbook.java , defines a Cookbook class that implements a
connect() method for connecting to the cookbook database. connect() returns a Con
nection object if it succeeds and throws an exception otherwise. To help the caller deal
with failures, the Cookbook class also defines getErrorMessage() and printErrorMes
sage() utility methods that return the error message as a string and print it to Sys
tem.err , respectively:
// Cookbook.java: library file with utility methods for connecting to MySQL
// using MySQL Connector/J and for handling exceptions
package com . kitebird . mcb ;
import java.sql.* ;
public class Cookbook
{
// Establish a connection to the cookbook database, returning
// a connection object. Throw an exception if the connection
// cannot be established.
public static Connection connect () throws Exception
{
String url = "jdbc:mysql://localhost/cookbook" ;
Search WWH ::




Custom Search