Database Reference
In-Depth Information
my $dsn = "DBI:mysql:database=cookbook" ;
# look in standard option files; use [cookbook] and [client] groups
$dsn .= ";mysql_read_default_group=cookbook" ;
my $dbh = DBI -> connect ( $dsn , undef , undef , $conn_attrs );
The next example explicitly names the option file located in $ENV{HOME} , the home
directory of the user running the script. Thus, MySQL looks only in that file and uses
options from the [client] group:
my $conn_attrs = { PrintError => 0 , RaiseError => 1 , AutoCommit => 1 };
# basic DSN
my $dsn = "DBI:mysql:database=cookbook" ;
# look in user-specific option file owned by the current user
$dsn .= ";mysql_read_default_file=$ENV{HOME}/.my.cnf" ;
my $dbh = DBI -> connect ( $dsn , undef , undef , $conn_attrs );
If you pass an empty value ( undef or the empty string) for the username or password
arguments of the connect() call, connect() uses whatever values are found in the op‐
tion file or files. A nonempty username or password in the connect() call overrides any
option-file value. Similarly, a host named in the DSN overrides any option-file value.
Use this behavior to enable DBI scripts to obtain connection parameters both from
option files as well as from the command line as follows:
1. Create $host_name , $user_name , and $password variables, each with a value of
undef . Then parse the command-line arguments to set the variables to non- undef
values if the corresponding options are present on the command line. (The
cmdline.pl Perl script under the api directory of the recipes distribution demon‐
strates how to do this.)
2. After parsing the command arguments, construct the DSN string, and call con
nect() . Use mysql_read_default_group and mysql_read_default_file in the
DSN to specify how you want option files to be used, and, if $host_name is not
undef , add host=$host_name to the DSN. In addition, pass $user_name and $pass
word as the username and password arguments to connect() . These will be un
def by default; if they were set from the command-line arguments, they will have
non- undef values that override any option-file values.
If a script follows this procedure, parameters given by the user on the command line
are passed to connect() and take precedence over the contents of option files.
Ruby. Ruby DBI scripts can access option files by using a mechanism analogous to that
used for Perl DBI, and the following examples correspond exactly to those shown in the
preceding Perl discussion.
This example uses the standard option-file search order to look for options in both the
[cookbook] and [client] groups:
Search WWH ::




Custom Search