Database Reference
In-Depth Information
String user = "cbuser" ;
String password = "cbpass" ;
Class . forName ( "com.mysql.jdbc.Driver" ). newInstance ();
return ( DriverManager . getConnection ( url , user , password ));
}
// Return an error message as a string
public static String getErrorMessage ( Exception e )
{
StringBuffer s = new StringBuffer ();
if ( e instanceof SQLException ) // JDBC-specific exception?
{
// print general message, plus any database-specific message
s . append ( "Error message: " + e . getMessage () + "\n" );
s . append ( "Error code: " + (( SQLException ) e ). getErrorCode () + "\n" );
}
else
{
s . append ( e + "\n" );
}
return ( s . toString ());
}
// Get the error message and print it to System.err
public static void printErrorMessage ( Exception e )
{
System . err . println ( Cookbook . getErrorMessage ( e ));
}
}
The routines within the class are declared using the static keyword, which makes them
class methods rather than instance methods. That is done here because the class is used
directly rather than creating an object from it and invoking the methods through the
object.
To use the Cookbook.java file, compile it to produce Cookbook.class , then install the
class file in a directory that corresponds to the package identifier. This means that
Cookbook.class should be installed in a directory named com/kitebird/mcb (Unix) or
com\kitebird\mcb (Windows) that is located under some directory named in your
CLASSPATH setting. For example, if CLASSPATH includes /usr/local/lib/mcb under Unix,
you can install Cookbook.class in the /usr/local/lib/mcb/com/kitebird/mcb directory.
(For more information about the CLASSPATH variable, see the Java discussion in
Recipe 2.1 .)
To use the Cookbook class from within a Java program, import it and invoke the Cook
book.connect() method. The following test harness program, Harness.java , shows how
to do this:
Search WWH ::




Custom Search