Database Reference
In-Depth Information
System . err . println ( "SQLException: " + e . getMessage ());
System . err . println ( "SQLState: " + e . getSQLState ());
System . err . println ( "Vendor code: " + e . getErrorCode ());
}
}
2.3. Writing Library Files
Problem
You notice that you're repeating code to perform common operations in multiple
programs.
Solution
Write routines to perform those operations, put them in a library file, and arrange for
your programs to access the library. This enables you to write the code only once. You
might need to set an environment variable so that your scripts can find the library.
Discussion
This section describes how to put code for common operations in library files. Encap‐
sulation (or modularization) isn't really a “recipe” so much as a programming technique.
Its principal benefit is that you need not repeat code in each program you write. Instead,
simply call a routine that's in the library. For example, by putting the code for connecting
to the cookbook database into a library routine, you need not write out all the parameters
associated with making that connection. Simply invoke the routine from your program,
and you're connected.
Connection establishment isn't the only operation you can encapsulate, of course. Later
sections in this topic develop other utility functions to be placed in library files. All such
files, including those shown in this section, are located under the lib directory of the
recipes distribution. As you write your own programs, be on the lookout for operations
that you perform often and that are good candidates for inclusion in a library. Use the
techniques in this section to write your own library files.
Library files have other benefits besides making it easier to write programs, such as
promoting portability. If you write connection parameters directly into each program
that connects to the MySQL server, you must change all those programs if you move
them to another machine that uses different parameters. If instead you write your pro‐
grams to connect to the database by calling a library routine, it's necessary only to modify
the affected library routine, not all the programs that use it.
Code encapsulation can also improve security. If you make a private library file readable
only to yourself, only scripts run by you can execute routines in the file. Or suppose
Search WWH ::




Custom Search