Database Reference
In-Depth Information
Writing library files
As you write program after program, you find that you carry out certain operations
repeatedly. Library files enable encapsulating code for those operations so they can
be performed easily from multiple scripts without repeating the code in each one.
This reduces code duplication and makes your programs more portable. This
chapter shows how to write a library file for each API that includes a routine for
connecting to the server—one operation that every program that uses MySQL must
perform. Later chapters develop additional library routines for other operations.
Additional techniques for obtaining connection parameters
An early section on establishing connections to the MySQL server relies on con‐
nection parameters hardwired into the code. However, there are other (and better)
ways to obtain parameters, ranging from storing them in a separate file to enabling
the user to specify them at runtime.
To avoid manually typing in the example programs, get a copy of the
recipes
source
distribution (see the
Preface
). Then, when an example says something like “create a file
named
xyz
that contains the following information ...,” you can use the corresponding
file from the
recipes
distribution. Most scripts for this chapter are located under the
api
directory; library files are located in the
lib
directory.
The primary table used for examples in this chapter is named
profile
. It first appears
in
Recipe 2.4
, which you should know in case you skip around in the chapter and wonder
where it came from. See also the section at the very end of the chapter about resetting
the
profile
table to a known state for use in other chapters.
The programs discussed here can be run from the command line. For
instructions on invoking programs for each language covered here,
read “Executing Programs from the Command Line” on the com‐
panion website (see the
Preface
).
Assumptions
To use the material in this chapter most effectively, make sure to satisfy these require‐
ments:
• Install MySQL programming support for any languages that you plan to use (see
the
Preface
).
• You should already have set up a MySQL user account for accessing the server and
a database for executing SQL statements. As described in
Recipe 1.1
, the examples
in this topic use a MySQL account that has a username and password of
cbuser
and
cbpass
, and we'll connect to a MySQL server running on the local host to access