home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / mysql.pm < prev    next >
Encoding:
Perl POD Document  |  2003-10-26  |  46.6 KB  |  1,754 lines

  1. #   -*- cperl -*-
  2.  
  3. package DBD::mysql;
  4. use strict;
  5. use vars qw(@ISA $VERSION $err $errstr $drh);
  6.  
  7. use DBI ();
  8. use DynaLoader();
  9. use Carp ();
  10. @ISA = qw(DynaLoader);
  11.  
  12. $VERSION = '2.9003';
  13.  
  14. bootstrap DBD::mysql $VERSION;
  15.  
  16.  
  17. $err = 0;    # holds error code   for DBI::err
  18. $errstr = "";    # holds error string for DBI::errstr
  19. $drh = undef;    # holds driver handle once initialised
  20.  
  21. sub driver{
  22.     return $drh if $drh;
  23.     my($class, $attr) = @_;
  24.  
  25.     $class .= "::dr";
  26.  
  27.     # not a 'my' since we use it above to prevent multiple drivers
  28.     $drh = DBI::_new_drh($class, { 'Name' => 'mysql',
  29.                    'Version' => $VERSION,
  30.                    'Err'    => \$DBD::mysql::err,
  31.                    'Errstr' => \$DBD::mysql::errstr,
  32.                    'Attribution' => 'DBD::mysql by Rudy Lippan'
  33.                  });
  34.  
  35.     $drh;
  36. }
  37.  
  38. sub CLONE {
  39.   undef $drh;
  40. }
  41.  
  42. sub _OdbcParse($$$) {
  43.     my($class, $dsn, $hash, $args) = @_;
  44.     my($var, $val);
  45.     if (!defined($dsn)) {
  46.     return;
  47.     }
  48.     while (length($dsn)) {
  49.     if ($dsn =~ /([^:;]*)[:;](.*)/) {
  50.         $val = $1;
  51.         $dsn = $2;
  52.     } else {
  53.         $val = $dsn;
  54.         $dsn = '';
  55.     }
  56.     if ($val =~ /([^=]*)=(.*)/) {
  57.         $var = $1;
  58.         $val = $2;
  59.         if ($var eq 'hostname'  ||  $var eq 'host') {
  60.         $hash->{'host'} = $val;
  61.         } elsif ($var eq 'db'  ||  $var eq 'dbname') {
  62.         $hash->{'database'} = $val;
  63.         } else {
  64.         $hash->{$var} = $val;
  65.         }
  66.     } else {
  67.         foreach $var (@$args) {
  68.         if (!defined($hash->{$var})) {
  69.             $hash->{$var} = $val;
  70.             last;
  71.         }
  72.         }
  73.     }
  74.     }
  75. }
  76.  
  77. sub _OdbcParseHost ($$) {
  78.     my($class, $dsn) = @_;
  79.     my($hash) = {};
  80.     $class->_OdbcParse($dsn, $hash, ['host', 'port']);
  81.     ($hash->{'host'}, $hash->{'port'});
  82. }
  83.  
  84. sub AUTOLOAD {
  85.     my ($meth) = $DBD::mysql::AUTOLOAD;
  86.     my ($smeth) = $meth;
  87.     $smeth =~ s/(.*)\:\://;
  88.  
  89.     my $val = constant($smeth, @_ ? $_[0] : 0);
  90.     if ($! == 0) { eval "sub $meth { $val }"; return $val; }
  91.  
  92.     Carp::croak "$meth: Not defined";
  93. }
  94.  
  95. 1;
  96.  
  97.  
  98. package DBD::mysql::dr; # ====== DRIVER ======
  99. use strict;
  100. use DBI qw(:sql_types);
  101.  
  102. sub connect {
  103.     my($drh, $dsn, $username, $password, $attrhash) = @_;
  104.     my($port);
  105.     my($cWarn);
  106.  
  107.     # Avoid warnings for undefined values
  108.     $username ||= '';
  109.     $password ||= '';
  110.  
  111.     # create a 'blank' dbh
  112.     my($this, $privateAttrHash) = (undef, $attrhash);
  113.     $privateAttrHash = { %$privateAttrHash,
  114.     'Name' => $dsn,
  115.     'user' => $username,
  116.     'password' => $password
  117.     };
  118.  
  119.     DBD::mysql->_OdbcParse($dsn, $privateAttrHash,
  120.                     ['database', 'host', 'port']);
  121.  
  122.     if (!defined($this = DBI::_new_dbh($drh, {'Name' => $dsn},
  123.                        $privateAttrHash))) {
  124.     return undef;
  125.     }
  126.  
  127.     # Call msqlConnect func in mSQL.xs file
  128.     # and populate internal handle data.
  129.     DBD::mysql::db::_login($this, $dsn, $username, $password)
  130.       or $this = undef;
  131.  
  132.     if ($this && ($ENV{MOD_PERL} || $ENV{GATEWAY_INTERFACE})) {
  133.         $this->{mysql_auto_reconnect} = 1;
  134.     }
  135.     $this;
  136. }
  137.  
  138. sub data_sources {
  139.     my($self) = shift;
  140.     my($attributes) = shift;
  141.     my($host, $port, $user, $password) = ('', '', '', '');
  142.     if ($attributes) {
  143.       $host = $attributes->{host} || '';
  144.       $port = $attributes->{port} || '';
  145.       $user = $attributes->{user} || '';
  146.       $password = $attributes->{password} || '';
  147.     }
  148.     my(@dsn) = $self->func($host, $port, $user, $password, '_ListDBs');
  149.     my($i);
  150.     for ($i = 0;  $i < @dsn;  $i++) {
  151.     $dsn[$i] = "DBI:mysql:$dsn[$i]";
  152.     }
  153.     @dsn;
  154. }
  155.  
  156. sub admin {
  157.     my($drh) = shift;
  158.     my($command) = shift;
  159.     my($dbname) = ($command eq 'createdb'  ||  $command eq 'dropdb') ?
  160.     shift : '';
  161.     my($host, $port) = DBD::mysql->_OdbcParseHost(shift(@_) || '');
  162.     my($user) = shift || '';
  163.     my($password) = shift || '';
  164.  
  165.     $drh->func(undef, $command,
  166.            $dbname || '',
  167.            $host || '',
  168.            $port || '',
  169.            $user, $password, '_admin_internal');
  170. }
  171.  
  172. package DBD::mysql::db; # ====== DATABASE ======
  173. use strict;
  174. use DBI qw(:sql_types);
  175.  
  176. %DBD::mysql::db::db2ANSI = ("INT"   =>  "INTEGER",
  177.                "CHAR"  =>  "CHAR",
  178.                "REAL"  =>  "REAL",
  179.                "IDENT" =>  "DECIMAL"
  180.                           );
  181.  
  182. ### ANSI datatype mapping to mSQL datatypes
  183. %DBD::mysql::db::ANSI2db = ("CHAR"          => "CHAR",
  184.                "VARCHAR"       => "CHAR",
  185.                "LONGVARCHAR"   => "CHAR",
  186.                "NUMERIC"       => "INTEGER",
  187.                "DECIMAL"       => "INTEGER",
  188.                "BIT"           => "INTEGER",
  189.                "TINYINT"       => "INTEGER",
  190.                "SMALLINT"      => "INTEGER",
  191.                "INTEGER"       => "INTEGER",
  192.                "BIGINT"        => "INTEGER",
  193.                "REAL"          => "REAL",
  194.                "FLOAT"         => "REAL",
  195.                "DOUBLE"        => "REAL",
  196.                "BINARY"        => "CHAR",
  197.                "VARBINARY"     => "CHAR",
  198.                "LONGVARBINARY" => "CHAR",
  199.                "DATE"          => "CHAR",
  200.                "TIME"          => "CHAR",
  201.                "TIMESTAMP"     => "CHAR"
  202.               );
  203.  
  204. sub prepare {
  205.     my($dbh, $statement, $attribs)= @_;
  206.  
  207.     # create a 'blank' dbh
  208.     my $sth = DBI::_new_sth($dbh, {'Statement' => $statement});
  209.  
  210.     # Populate internal handle data.
  211.     if (!DBD::mysql::st::_prepare($sth, $statement, $attribs)) {
  212.     $sth = undef;
  213.     }
  214.  
  215.     $sth;
  216. }
  217.  
  218. sub db2ANSI {
  219.     my $self = shift;
  220.     my $type = shift;
  221.     return $DBD::mysql::db::db2ANSI{"$type"};
  222. }
  223.  
  224. sub ANSI2db {
  225.     my $self = shift;
  226.     my $type = shift;
  227.     return $DBD::mysql::db::ANSI2db{"$type"};
  228. }
  229.  
  230. sub admin {
  231.     my($dbh) = shift;
  232.     my($command) = shift;
  233.     my($dbname) = ($command eq 'createdb'  ||  $command eq 'dropdb') ?
  234.     shift : '';
  235.     $dbh->{'Driver'}->func($dbh, $command, $dbname, '', '', '',
  236.                '_admin_internal');
  237. }
  238.  
  239. sub _SelectDB ($$) {
  240.     die "_SelectDB is removed from this module; use DBI->connect instead.";
  241. }
  242.  
  243. {
  244.     my $names = ['TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME',
  245.          'TABLE_TYPE', 'REMARKS'];
  246.  
  247.     sub table_info ($) {
  248.     my $dbh = shift;
  249.     my $sth = $dbh->prepare("SHOW TABLES");
  250.     return undef unless $sth;
  251.     if (!$sth->execute()) {
  252.       return DBI::set_err($dbh, $sth->err(), $sth->errstr());
  253.         }
  254.     my @tables;
  255.     while (my $ref = $sth->fetchrow_arrayref()) {
  256.       push(@tables, [ undef, undef, $ref->[0], 'TABLE', undef ]);
  257.         }
  258.     my $dbh2;
  259.     if (!($dbh2 = $dbh->{'~dbd_driver~_sponge_dbh'})) {
  260.         $dbh2 = $dbh->{'~dbd_driver~_sponge_dbh'} =
  261.         DBI->connect("DBI:Sponge:");
  262.         if (!$dbh2) {
  263.             DBI::set_err($dbh, 1, $DBI::errstr);
  264.         return undef;
  265.         }
  266.     }
  267.     my $sth2 = $dbh2->prepare("SHOW TABLES", { 'rows' => \@tables,
  268.                            'NAME' => $names,
  269.                            'NUM_OF_FIELDS' => 5 });
  270.     if (!$sth2) {
  271.         DBI::set_err($sth2, $dbh2->err(), $dbh2->errstr());
  272.     }
  273.     $sth2;
  274.     }
  275. }
  276.  
  277. sub _ListTables {
  278.   my $dbh = shift;
  279.   if (!$DBD::mysql::QUIET) {
  280.     warn "_ListTables is deprecated, use \$dbh->tables()";
  281.   }
  282.   return map { $_ =~ s/.*\.//; $_ } $dbh->tables();
  283. }
  284.  
  285.  
  286. sub column_info {
  287.     my ($dbh, $catalog, $schema, $table, $column) = @_;
  288.     return $dbh->set_err(1, "column_info doesn't support table wildcard")
  289.     if $table !~ /^\w+$/;
  290.     return $dbh->set_err(1, "column_info doesn't support column selection")
  291.     if $column ne "%";
  292.  
  293.     my $table_id = $dbh->quote_identifier($catalog, $schema, $table);
  294.  
  295.     my @names = qw(
  296.     TABLE_CAT TABLE_SCHEM TABLE_NAME COLUMN_NAME
  297.     DATA_TYPE TYPE_NAME COLUMN_SIZE BUFFER_LENGTH DECIMAL_DIGITS
  298.     NUM_PREC_RADIX NULLABLE REMARKS COLUMN_DEF
  299.     SQL_DATA_TYPE SQL_DATETIME_SUB CHAR_OCTET_LENGTH
  300.     ORDINAL_POSITION IS_NULLABLE CHAR_SET_CAT
  301.     CHAR_SET_SCHEM CHAR_SET_NAME COLLATION_CAT COLLATION_SCHEM COLLATION_NAME
  302.     UDT_CAT UDT_SCHEM UDT_NAME DOMAIN_CAT DOMAIN_SCHEM DOMAIN_NAME
  303.     SCOPE_CAT SCOPE_SCHEM SCOPE_NAME MAX_CARDINALITY
  304.     DTD_IDENTIFIER IS_SELF_REF
  305.     mysql_is_pri_key mysql_type_name mysql_values
  306.     );
  307.     my %col_info;
  308.  
  309.     local $dbh->{FetchHashKeyName} = 'NAME_lc';
  310.     my $desc_sth = $dbh->prepare("DESCRIBE $table_id");
  311.     my $desc = $dbh->selectall_arrayref($desc_sth, { Columns=>{} });
  312.     my $ordinal_pos = 0;
  313.     foreach my $row (@$desc) {
  314.     my $type = $row->{type};
  315.     $type =~ m/^(\w+)(?:\((.*?)\))?\s*(.*)/;
  316.     my $basetype = lc($1);
  317.  
  318.     my $info = $col_info{ $row->{field} } = {
  319.         TABLE_CAT   => $catalog,
  320.         TABLE_SCHEM => $schema,
  321.         TABLE_NAME  => $table,
  322.         COLUMN_NAME => $row->{field},
  323.         NULLABLE    => ($row->{null} eq 'YES') ? 1 : 0,
  324.         IS_NULLABLE => ($row->{null} eq 'YES') ? "YES" : "NO",
  325.         TYPE_NAME   => uc($basetype),
  326.         COLUMN_DEF  => $row->{default},
  327.         ORDINAL_POSITION => ++$ordinal_pos,
  328.         mysql_is_pri_key => ($row->{key}  eq 'PRI'),
  329.         mysql_type_name  => $row->{type},
  330.     };
  331.     # This code won't deal with a pathalogical case where a value
  332.     # contains a single quote followed by a comma, and doesn't unescape
  333.     # any escaped values. But who would use those in an enum or set?
  334.     my @type_params = ($2 && index($2,"'")>=0)
  335.             ? ("$2," =~ /'(.*?)',/g)  # assume all are quoted
  336.             : split /,/, $2||'';      # no quotes, plain list
  337.     s/''/'/g for @type_params;                # undo doubling of quotes
  338.     my @type_attr = split / /, $3||'';
  339.     #warn "$type: $basetype [@type_params] [@type_attr]\n";
  340.  
  341.     $info->{DATA_TYPE} = SQL_VARCHAR();
  342.     if ($basetype =~ /char|text|blob/) {
  343.         $info->{DATA_TYPE} = SQL_CHAR() if $basetype eq 'char';
  344.         if ($type_params[0]) {
  345.         $info->{COLUMN_SIZE} = $type_params[0];
  346.         }
  347.         else {
  348.         $info->{COLUMN_SIZE} = 65535;
  349.         $info->{COLUMN_SIZE} = 255        if $basetype =~ /^tiny/;
  350.         $info->{COLUMN_SIZE} = 16777215   if $basetype =~ /^medium/;
  351.         $info->{COLUMN_SIZE} = 4294967295 if $basetype =~ /^long/;
  352.         }
  353.     }
  354.     elsif ($basetype =~ /enum|set/) {
  355.         if ($basetype eq 'set') {
  356.         $info->{COLUMN_SIZE} = length(join ",", @type_params);
  357.         }
  358.         else {
  359.         my $max_len = 0;
  360.         length($_) > $max_len and $max_len = length($_) for @type_params;
  361.         $info->{COLUMN_SIZE} = $max_len;
  362.         }
  363.         $info->{"mysql_values"} = \@type_params;
  364.     }
  365.     elsif ($basetype =~ /int/) {
  366.         $info->{DATA_TYPE} = SQL_INTEGER();
  367.         $info->{NUM_PREC_RADIX} = 10;
  368.         $info->{COLUMN_SIZE} = $type_params[0];
  369.     }
  370.     elsif ($basetype =~ /decimal/) {
  371.         $info->{DATA_TYPE} = SQL_DECIMAL();
  372.         $info->{NUM_PREC_RADIX} = 10;
  373.         $info->{COLUMN_SIZE}    = $type_params[0];
  374.         $info->{DECIMAL_DIGITS} = $type_params[1];
  375.     }
  376.     elsif ($basetype =~ /float|double/) {
  377.         $info->{DATA_TYPE} = ($basetype eq 'float') ? SQL_FLOAT() : SQL_DOUBLE();
  378.         $info->{NUM_PREC_RADIX} = 2;
  379.         $info->{COLUMN_SIZE} = ($basetype eq 'float') ? 32 : 64;
  380.     }
  381.     elsif ($basetype =~ /date|time/) { # date/datetime/time/timestamp
  382.         if ($basetype eq 'time' or $basetype eq 'date') {
  383.         $info->{DATA_TYPE}   = ($basetype eq 'time') ? SQL_TYPE_TIME() : SQL_TYPE_DATE();
  384.         $info->{COLUMN_SIZE} = ($basetype eq 'time') ? 8 : 10;
  385.         }
  386.         else { # datetime/timestamp
  387.         $info->{DATA_TYPE}     = SQL_TYPE_TIMESTAMP();
  388.         $info->{SQL_DATA_TYPE} = SQL_DATETIME();
  389.             $info->{SQL_DATETIME_SUB} = $info->{DATA_TYPE} - ($info->{SQL_DATA_TYPE} * 10);
  390.         $info->{COLUMN_SIZE}   = ($basetype eq 'datetime') ? 19 : $type_params[0] || 14;
  391.         }
  392.         $info->{DECIMAL_DIGITS} = 0; # no fractional seconds
  393.     }
  394.     else {
  395.         warn "unsupported column '$row->{field}' type '$basetype' treated as varchar";
  396.     }
  397.     $info->{SQL_DATA_TYPE} ||= $info->{DATA_TYPE};
  398.     #warn Dumper($info);
  399.     }
  400.  
  401.     my $sponge = DBI->connect("DBI:Sponge:", '','')
  402.     or return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr");
  403.     my $sth = $sponge->prepare("column_info $table", {
  404.     rows => [ map { [ @{$_}{@names} ] } values %col_info ],
  405.     NUM_OF_FIELDS => scalar @names,
  406.     NAME => \@names,
  407.     }) or return $dbh->DBI::set_err($sponge->err(), $sponge->errstr());
  408.  
  409.     return $sth;
  410. }
  411.  
  412.  
  413.  
  414. ####################
  415. # get_info()
  416. # Generated by DBI::DBD::Metadata
  417.  
  418. sub get_info {
  419.     my($dbh, $info_type) = @_;
  420.     require DBD::mysql::GetInfo;
  421.     my $v = $DBD::mysql::GetInfo::info{int($info_type)};
  422.     $v = $v->($dbh) if ref $v eq 'CODE';
  423.     return $v;
  424. }
  425.  
  426.  
  427.  
  428. package DBD::mysql::st; # ====== STATEMENT ======
  429. use strict;
  430.  
  431. 1;
  432.  
  433. __END__
  434.  
  435. =pod
  436.  
  437. =head1 NAME
  438.  
  439. DBD::mysql - MySQL driver for the Perl5 Database Interface (DBI)
  440.  
  441. =head1 SYNOPSIS
  442.  
  443.     use DBI;
  444.  
  445.     $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
  446.  
  447.     $dbh = DBI->connect($dsn, $user, $password);
  448.  
  449.  
  450.     $drh = DBI->install_driver("mysql");
  451.     @databases = DBI->data_sources("mysql");
  452.        or
  453.     @databases = DBI->data_sources("mysql",
  454.                    {"host" => $host, "port" => $port});
  455.  
  456.     $sth = $dbh->prepare("SELECT * FROM foo WHERE bla");
  457.        or
  458.     $sth = $dbh->prepare("LISTFIELDS $table");
  459.        or
  460.     $sth = $dbh->prepare("LISTINDEX $table $index");
  461.     $sth->execute;
  462.     $numRows = $sth->rows;
  463.     $numFields = $sth->{'NUM_OF_FIELDS'};
  464.     $sth->finish;
  465.  
  466.     $rc = $drh->func('createdb', $database, $host, $user, $password, 'admin');
  467.     $rc = $drh->func('dropdb', $database, $host, $user, $password, 'admin');
  468.     $rc = $drh->func('shutdown', $host, $user, $password, 'admin');
  469.     $rc = $drh->func('reload', $host, $user, $password, 'admin');
  470.  
  471.     $rc = $dbh->func('createdb', $database, 'admin');
  472.     $rc = $dbh->func('dropdb', $database, 'admin');
  473.     $rc = $dbh->func('shutdown', 'admin');
  474.     $rc = $dbh->func('reload', 'admin');
  475.  
  476.  
  477. =head1 EXAMPLE
  478.  
  479.   #!/usr/bin/perl
  480.  
  481.   use strict;
  482.   use DBI();
  483.  
  484.   # Connect to the database.
  485.   my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost",
  486.                          "joe", "joe's password",
  487.                          {'RaiseError' => 1});
  488.  
  489.   # Drop table 'foo'. This may fail, if 'foo' doesn't exist.
  490.   # Thus we put an eval around it.
  491.   eval { $dbh->do("DROP TABLE foo") };
  492.   print "Dropping foo failed: $@\n" if $@;
  493.  
  494.   # Create a new table 'foo'. This must not fail, thus we don't
  495.   # catch errors.
  496.   $dbh->do("CREATE TABLE foo (id INTEGER, name VARCHAR(20))");
  497.  
  498.   # INSERT some data into 'foo'. We are using $dbh->quote() for
  499.   # quoting the name.
  500.   $dbh->do("INSERT INTO foo VALUES (1, " . $dbh->quote("Tim") . ")");
  501.  
  502.   # Same thing, but using placeholders
  503.   $dbh->do("INSERT INTO foo VALUES (?, ?)", undef, 2, "Jochen");
  504.  
  505.   # Now retrieve data from the table.
  506.   my $sth = $dbh->prepare("SELECT * FROM foo");
  507.   $sth->execute();
  508.   while (my $ref = $sth->fetchrow_hashref()) {
  509.     print "Found a row: id = $ref->{'id'}, name = $ref->{'name'}\n";
  510.   }
  511.   $sth->finish();
  512.  
  513.   # Disconnect from the database.
  514.   $dbh->disconnect();
  515.  
  516.  
  517. =head1 DESCRIPTION
  518.  
  519. B<DBD::mysql> is the Perl5 Database Interface driver for the MySQL
  520. database. In other words: DBD::mysql is an interface between the Perl
  521. programming language and the MySQL programming API that comes with
  522. the MySQL relational database management system. Most functions
  523. provided by this programming API are supported. Some rarely used
  524. functions are missing, mainly because noone ever requested
  525. them. :-)
  526.  
  527. In what follows we first discuss the use of DBD::mysql,
  528. because this is what you will need the most. For installation, see the
  529. sections on L<INSTALLATION>, L<WIN32 INSTALLATION>, and L<KNOWN BUGS>
  530. below. See L<EXAMPLE> for a simple example above.
  531.  
  532. From perl you activate the interface with the statement
  533.  
  534.     use DBI;
  535.  
  536. After that you can connect to multiple MySQL database servers
  537. and send multiple queries to any of them via a simple object oriented
  538. interface. Two types of objects are available: database handles and
  539. statement handles. Perl returns a database handle to the connect
  540. method like so:
  541.  
  542.   $dbh = DBI->connect("DBI:mysql:database=$db;host=$host",
  543.               $user, $password, {RaiseError => 1});
  544.  
  545. Once you have connected to a database, you can can execute SQL
  546. statements with:
  547.  
  548.   my $query = sprintf("INSERT INTO foo VALUES (%d, %s)",
  549.               $number, $dbh->quote("name"));
  550.   $dbh->do($query);
  551.  
  552. See L<DBI(3)> for details on the quote and do methods. An alternative
  553. approach is
  554.  
  555.   $dbh->do("INSERT INTO foo VALUES (?, ?)", undef,
  556.        $number, $name);
  557.  
  558. in which case the quote method is executed automatically. See also
  559. the bind_param method in L<DBI(3)>. See L<DATABASE HANDLES> below
  560. for more details on database handles.
  561.  
  562. If you want to retrieve results, you need to create a so-called
  563. statement handle with:
  564.  
  565.   $sth = $dbh->prepare("SELECT * FROM $table");
  566.   $sth->execute();
  567.  
  568. This statement handle can be used for multiple things. First of all
  569. you can retreive a row of data:
  570.  
  571.   my $row = $sth->fetchow_hashref();
  572.  
  573. If your table has columns ID and NAME, then $row will be hash ref with
  574. keys ID and NAME. See L<STATEMENT HANDLES> below for more details on
  575. statement handles.
  576.  
  577. But now for a more formal approach:
  578.  
  579.  
  580. =head2 Class Methods
  581.  
  582. =over
  583.  
  584. =item B<connect>
  585.  
  586.     use DBI;
  587.  
  588.     $dsn = "DBI:mysql:$database";
  589.     $dsn = "DBI:mysql:database=$database;host=$hostname";
  590.     $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
  591.  
  592.     $dbh = DBI->connect($dsn, $user, $password);
  593.  
  594. A C<database> must always be specified.
  595.  
  596. =over
  597.  
  598. =item host
  599.  
  600. =item port
  601.  
  602. The hostname, if not specified or specified as '', will default to an
  603. MySQL daemon running on the local machine on the default port
  604. for the UNIX socket.
  605.  
  606. Should the MySQL daemon be running on a non-standard port number,
  607. you may explicitly state the port number to connect to in the C<hostname>
  608. argument, by concatenating the I<hostname> and I<port number> together
  609. separated by a colon ( C<:> ) character or by using the  C<port> argument.
  610.  
  611.  
  612. =item mysql_client_found_rows
  613.  
  614. Enables (TRUE value) or disables (FALSE value) the flag CLIENT_FOUND_ROWS
  615. while connecting to the MySQL server. This has a somewhat funny effect:
  616. Without mysql_client_found_rows, if you perform a query like
  617.  
  618.   UPDATE $table SET id = 1 WHERE id = 1
  619.  
  620. then the MySQL engine will always return 0, because no rows have changed.
  621. With mysql_client_found_rows however, it will return the number of rows
  622. that have an id 1, as some people are expecting. (At least for compatibility
  623. to other engines.)
  624.  
  625. =item mysql_compression
  626.  
  627. As of MySQL 3.22.3, a new feature is supported: If your DSN contains
  628. the option "mysql_compression=1", then the communication between client
  629. and server will be compressed.
  630.  
  631. =item mysql_connect_timeout
  632.  
  633. If your DSN contains the option "mysql_connect_timeout=##", the connect
  634. request to the server will timeout if it has not been successful after
  635. the given number of seconds.
  636.  
  637. =item mysql_read_default_file
  638.  
  639. =item mysql_read_default_group
  640.  
  641. These options can be used to read a config file like /etc/my.cnf or
  642. ~/.my.cnf. By default MySQL's C client library doesn't use any config
  643. files unlike the client programs (mysql, mysqladmin, ...) that do, but
  644. outside of the C client library. Thus you need to explicitly request
  645. reading a config file, as in
  646.  
  647.     $dsn = "DBI:mysql:test;mysql_read_default_file=/home/joe/my.cnf";
  648.     $dbh = DBI->connect($dsn, $user, $password)
  649.  
  650. The option mysql_read_default_group can be used to specify the default
  651. group in the config file: Usually this is the I<client> group, but
  652. see the following example:
  653.  
  654.     [client]
  655.     host=localhost
  656.  
  657.     [perl]
  658.     host=perlhost
  659.  
  660. (Note the order of the entries! The example won't work, if you reverse
  661. the [client] and [perl] sections!)
  662.  
  663. If you read this config file, then you'll be typically connected to
  664. I<localhost>. However, by using
  665.  
  666.     $dsn = "DBI:mysql:test;mysql_read_default_group=perl;"
  667.         . "mysql_read_default_file=/home/joe/my.cnf";
  668.     $dbh = DBI->connect($dsn, $user, $password);
  669.  
  670. you'll be connected to I<perlhost>. Note that if you specify a
  671. default group and do not specify a file, then the default config
  672. files will all be read.  See the documentation of
  673. the C function mysql_options() for details.
  674.  
  675. =item mysql_socket
  676.  
  677. As of MySQL 3.21.15, it is possible to choose the Unix socket that is
  678. used for connecting to the server. This is done, for example, with
  679.  
  680.     mysql_socket=/dev/mysql
  681.  
  682. Usually there's no need for this option, unless you are using another
  683. location for the socket than that built into the client.
  684.  
  685. =item mysql_ssl
  686.  
  687. A true value turns on the CLIENT_SSL flag when connecting to the MySQL
  688. database:
  689.  
  690.   mysql_ssl=1
  691.  
  692. This means that your communication with the server will be encrypted.
  693.  
  694. If you turn mysql_ssl on, you might also wish to use the following
  695. flags:
  696.  
  697. =item mysql_ssl_client_key
  698.  
  699. =item mysql_ssl_client_cert
  700.  
  701. =item mysql_ssl_ca_file
  702.  
  703. =item mysql_ssl_ca_path
  704.  
  705. =item mysql_ssl_cipher
  706.  
  707. These are used to specify the respective parameters of a call
  708. to mysql_ssl_set, if mysql_ssl is turned on.  
  709.  
  710.  
  711. =item mysql_local_infile
  712.  
  713. As of MySQL 3.23.49, the LOCAL capability for LOAD DATA may be disabled
  714. in the MySQL client library by default. If your DSN contains the option
  715. "mysql_local_infile=1", LOAD DATA LOCAL will be enabled.  (However,
  716. this option is effective if the server has also been configured to
  717. disallow LOCAL.)
  718.  
  719.  
  720. =back
  721.  
  722. =back
  723.  
  724.  
  725. =head2 Private MetaData Methods
  726.  
  727. =over
  728.  
  729. =item B<ListDBs>
  730.  
  731.     my $drh = DBI->install_driver("mysql");
  732.     @dbs = $drh->func("$hostname:$port", '_ListDBs');
  733.     @dbs = $drh->func($hostname, $port, '_ListDBs');
  734.     @dbs = $dbh->func('_ListDBs');
  735.  
  736. Returns a list of all databases managed by the MySQL daemon
  737. running on C<$hostname>, port C<$port>. This method
  738. is rarely needed for databases running on C<localhost>: You should
  739. use the portable method
  740.  
  741.     @dbs = DBI->data_sources("mysql");
  742.  
  743. whenever possible. It is a design problem of this method, that there's
  744. no way of supplying a host name or port number to C<data_sources>, that's
  745. the only reason why we still support C<ListDBs>. :-(
  746.  
  747. =back
  748.  
  749.  
  750. =head2 Server Administration
  751.  
  752. =over
  753.  
  754. =item admin
  755.  
  756.     $rc = $drh->func("createdb", $dbname, [host, user, password,], 'admin');
  757.     $rc = $drh->func("dropdb", $dbname, [host, user, password,], 'admin');
  758.     $rc = $drh->func("shutdown", [host, user, password,], 'admin');
  759.     $rc = $drh->func("reload", [host, user, password,], 'admin');
  760.  
  761.       or
  762.  
  763.     $rc = $dbh->func("createdb", $dbname, 'admin');
  764.     $rc = $dbh->func("dropdb", $dbname, 'admin');
  765.     $rc = $dbh->func("shutdown", 'admin');
  766.     $rc = $dbh->func("reload", 'admin');
  767.  
  768. For server administration you need a server connection. For obtaining
  769. this connection you have two options: Either use a driver handle (drh)
  770. and supply the appropriate arguments (host, defaults localhost, user,
  771. defaults to '' and password, defaults to ''). A driver handle can be
  772. obtained with
  773.  
  774.     $drh = DBI->install_driver('mysql');
  775.  
  776. Otherwise reuse the existing connection of a database handle (dbh).
  777.  
  778. There's only one function available for administrative purposes, comparable
  779. to the m(y)sqladmin programs. The command being execute depends on the
  780. first argument:
  781.  
  782. =over
  783.  
  784. =item createdb
  785.  
  786. Creates the database $dbname. Equivalent to "m(y)sqladmin create $dbname".
  787.  
  788. =item dropdb
  789.  
  790. Drops the database $dbname. Equivalent to "m(y)sqladmin drop $dbname".
  791.  
  792. It should be noted that database deletion is
  793. I<not prompted for> in any way.  Nor is it undo-able from DBI.
  794.  
  795.     Once you issue the dropDB() method, the database will be gone!
  796.  
  797. These method should be used at your own risk.
  798.  
  799. =item shutdown
  800.  
  801. Silently shuts down the database engine. (Without prompting!)
  802. Equivalent to "m(y)sqladmin shutdown".
  803.  
  804. =item reload
  805.  
  806. Reloads the servers configuration files and/or tables. This can be particularly
  807. important if you modify access privileges or create new users.
  808.  
  809. =back
  810.  
  811. =back
  812.  
  813.  
  814. =head1 DATABASE HANDLES
  815.  
  816. The DBD::mysql driver supports the following attributes of database
  817. handles (read only):
  818.  
  819.   $errno = $dbh->{'mysql_errno'};
  820.   $error = $dbh->{'mysql_error};
  821.   $info = $dbh->{'mysql_hostinfo'};
  822.   $info = $dbh->{'mysql_info'};
  823.   $insertid = $dbh->{'mysql_insertid'};
  824.   $info = $dbh->{'mysql_protoinfo'};
  825.   $info = $dbh->{'mysql_serverinfo'};
  826.   $info = $dbh->{'mysql_stat'};
  827.   $threadId = $dbh->{'mysql_thread_id'};
  828.  
  829. These correspond to mysql_errno(), mysql_error(), mysql_get_host_info(),
  830. mysql_info(), mysql_insert_id(), mysql_get_proto_info(),
  831. mysql_get_server_info(), mysql_stat() and mysql_thread_id(),
  832. respectively.
  833.  
  834.  
  835.  $info_hashref = $dhb->{mysql_dbd_stats}
  836.  
  837. DBD::mysql keeps track of some statistics in the mysql_dbd_stats attribute.
  838. The following stats are being maintained:
  839.  
  840. =over
  841.  
  842. =item auto_reconnects_ok
  843.  
  844. the number of times that DBD::mysql had to reconnect to mysql
  845.  
  846. =item failed_auto_reconnects_failed
  847.  
  848. the number of times that DBD::mysql tried to reconnect to mysql but failed.
  849.  
  850. =back
  851.  
  852. The DBD::mysql driver also supports the following attribute(s) of database
  853. handles (read/write):
  854.  
  855.  $bool_value = $dbh->{mysql_auto_reconnect};
  856.  $dbh->{mysql_auto_reconnect} = $AutoReconnect ? 1 : 0;
  857.  
  858.  
  859. =item mysql_auto_reconnect
  860.  
  861. This attribute determines whether DBD::mysql will automatically reconnect
  862. to mysql if the connection be lost. This feature defaults to off; however,
  863. if either the GATEWAY_INTERFACE or MOD_PERL envionment variable is set, 
  864. DBD::mysql will turn mysql_auto_reconnect on.  Setting mysql_auto_reconnect 
  865. to on is not advised if 'lock tables' is used because if DBD::mysql reconnect 
  866. to mysql all table locks will be lost.  This attribute is ignored when
  867. AutoCommit is turned off, and when AutoCommit is turned off, DBD::mysql will
  868. not automatically reconnect to the server.
  869.  
  870. =head1 STATEMENT HANDLES
  871.  
  872. The statement handles of DBD::mysql support a number
  873. of attributes. You access these by using, for example,
  874.  
  875.   my $numFields = $sth->{'NUM_OF_FIELDS'};
  876.  
  877. Note, that most attributes are valid only after a successfull I<execute>.
  878. An C<undef> value will returned in that case. The most important exception
  879. is the C<mysql_use_result> attribute: This forces the driver to use
  880. mysql_use_result rather than mysql_store_result. The former is faster
  881. and less memory consuming, but tends to block other processes. (That's why
  882. mysql_store_result is the default.)
  883.  
  884. To set the C<mysql_use_result> attribute, use either of the following:
  885.  
  886.   my $sth = $dbh->prepare("QUERY", { "mysql_use_result" => 1});
  887.  
  888. or
  889.  
  890.   my $sth = $dbh->prepare("QUERY");
  891.   $sth->{"mysql_use_result"} = 1;
  892.  
  893. Column dependent attributes, for example I<NAME>, the column names,
  894. are returned as a reference to an array. The array indices are
  895. corresponding to the indices of the arrays returned by I<fetchrow>
  896. and similar methods. For example the following code will print a
  897. header of table names together with all rows:
  898.  
  899.   my $sth = $dbh->prepare("SELECT * FROM $table");
  900.   if (!$sth) {
  901.       die "Error:" . $dbh->errstr . "\n";
  902.   }
  903.   if (!$sth->execute) {
  904.       die "Error:" . $sth->errstr . "\n";
  905.   }
  906.   my $names = $sth->{'NAME'};
  907.   my $numFields = $sth->{'NUM_OF_FIELDS'};
  908.   for (my $i = 0;  $i < $numFields;  $i++) {
  909.       printf("%s%s", $i ? "," : "", $$names[$i]);
  910.   }
  911.   print "\n";
  912.   while (my $ref = $sth->fetchrow_arrayref) {
  913.       for (my $i = 0;  $i < $numFields;  $i++) {
  914.       printf("%s%s", $i ? "," : "", $$ref[$i]);
  915.       }
  916.       print "\n";
  917.   }
  918.  
  919. For portable applications you should restrict yourself to attributes with
  920. capitalized or mixed case names. Lower case attribute names are private
  921. to DBD::mysql. The attribute list includes:
  922.  
  923. =over
  924.  
  925. =item ChopBlanks
  926.  
  927. this attribute determines whether a I<fetchrow> will chop preceding
  928. and trailing blanks off the column values. Chopping blanks does not
  929. have impact on the I<max_length> attribute.
  930.  
  931. =item mysql_insertid
  932.  
  933. MySQL has the ability to choose unique key values automatically. If this
  934. happened, the new ID will be stored in this attribute. An alternative
  935. way for accessing this attribute is via $dbh->{'mysql_insertid'}.
  936. (Note we are using the $dbh in this case!)
  937.  
  938. =item mysql_is_blob
  939.  
  940. Reference to an array of boolean values; TRUE indicates, that the
  941. respective column is a blob. This attribute is valid for MySQL only.
  942.  
  943. =item mysql_is_key
  944.  
  945. Reference to an array of boolean values; TRUE indicates, that the
  946. respective column is a key. This is valid for MySQL only.
  947.  
  948. =item mysql_is_num
  949.  
  950. Reference to an array of boolean values; TRUE indicates, that the
  951. respective column contains numeric values.
  952.  
  953. =item mysql_is_pri_key
  954.  
  955. Reference to an array of boolean values; TRUE indicates, that the
  956. respective column is a primary key.
  957.  
  958. =item mysql_is_auto_increment
  959.  
  960. Reference to an array of boolean values; TRUE indicates that the
  961. respective column is an AUTO_INCREMENT column.  This is only valid
  962. for MySQL.
  963.  
  964. =item mysql_length
  965.  
  966. =item mysql_max_length
  967.  
  968. A reference to an array of maximum column sizes. The I<max_length> is
  969. the maximum physically present in the result table, I<length> gives
  970. the theoretically possible maximum. I<max_length> is valid for MySQL
  971. only.
  972.  
  973. =item NAME
  974.  
  975. A reference to an array of column names.
  976.  
  977. =item NULLABLE
  978.  
  979. A reference to an array of boolean values; TRUE indicates that this column
  980. may contain NULL's.
  981.  
  982. =item NUM_OF_FIELDS
  983.  
  984. Number of fields returned by a I<SELECT> or I<LISTFIELDS> statement.
  985. You may use this for checking whether a statement returned a result:
  986. A zero value indicates a non-SELECT statement like I<INSERT>,
  987. I<DELETE> or I<UPDATE>.
  988.  
  989. =item mysql_table
  990.  
  991. A reference to an array of table names, useful in a I<JOIN> result.
  992.  
  993. =item TYPE
  994.  
  995. A reference to an array of column types. The engine's native column
  996. types are mapped to portable types like DBI::SQL_INTEGER() or
  997. DBI::SQL_VARCHAR(), as good as possible. Not all native types have
  998. a meaningfull equivalent, for example DBD::mysql::FIELD_TYPE_INTERVAL
  999. is mapped to DBI::SQL_VARCHAR().
  1000. If you need the native column types, use I<mysql_type>. See below.
  1001.  
  1002. =item mysql_type
  1003.  
  1004. A reference to an array of MySQL's native column types, for example
  1005. DBD::mysql::FIELD_TYPE_SHORT() or DBD::mysql::FIELD_TYPE_STRING().
  1006. Use the I<TYPE> attribute, if you want portable types like
  1007. DBI::SQL_SMALLINT() or DBI::SQL_VARCHAR().
  1008.  
  1009. =item mysql_type_name
  1010.  
  1011. Similar to mysql, but type names and not numbers are returned.
  1012. Whenever possible, the ANSI SQL name is preferred.
  1013.  
  1014. =back
  1015.  
  1016.  
  1017. =head1 TRANSACTION SUPPORT
  1018.  
  1019. Beginning with DBD::mysql 2.0416, transactions are supported.
  1020. The transaction support works as follows:
  1021.  
  1022. =over
  1023.  
  1024. =item *
  1025.  
  1026. By default AutoCommit mode is on, following the DBI specifications.
  1027.  
  1028. =item *
  1029.  
  1030. If you execute
  1031.  
  1032.     $dbh-E<gt>{'AutoCommit'} = 0;
  1033.  
  1034. or
  1035.  
  1036.     $dbh-E<gt>{'AutoCommit'} = 1;
  1037.  
  1038. then the driver will set the MySQL server variable autocommit to 0 or
  1039. 1, respectively. Switching from 0 to 1 will also issue a COMMIT,
  1040. following the DBI specifications.
  1041.  
  1042. =item *
  1043.  
  1044. The methods
  1045.  
  1046.     $dbh-E<gt>rollback();
  1047.     $dbh-E<gt>commit();
  1048.  
  1049. will issue the commands COMMIT and ROLLBACK, respectively. A
  1050. ROLLBACK will also be issued if AutoCommit mode is off and the
  1051. database handles DESTROY method is called. Again, this is following
  1052. the DBI specifications.
  1053.  
  1054. =back
  1055.  
  1056. Given the above, you should note the following:
  1057.  
  1058. =over
  1059.  
  1060. =item *
  1061.  
  1062. You should never change the server variable autocommit manually,
  1063. unless you are ignoring DBI's transaction support.
  1064.  
  1065. =item *
  1066.  
  1067. Switching AutoCommit mode from on to off or vice versa may fail.
  1068. You should always check for errors, when changing AutoCommit mode.
  1069. The suggested way of doing so is using the DBI flag RaiseError.
  1070. If you don't like RaiseError, you have to use code like the
  1071. following:
  1072.  
  1073.   $dbh->{'AutoCommit'} = 0;
  1074.   if ($dbh->{'AutoCommit'}) {
  1075.     # An error occurred!
  1076.   }
  1077.  
  1078. =item *
  1079.  
  1080. If you detect an error while changing the AutoCommit mode, you
  1081. should no longer use the database handle. In other words, you
  1082. should disconnect and reconnect again, because the transaction
  1083. mode is unpredictable. Alternatively you may verify the transaction
  1084. mode by checking the value of the server variable autocommit.
  1085. However, such behaviour isn't portable.
  1086.  
  1087. =item *
  1088.  
  1089. DBD::mysql has a "reconnect" feature that handles the so-called
  1090. MySQL "morning bug": If the server has disconnected, most probably
  1091. due to a timeout, then by default the driver will reconnect and
  1092. attempt to execute the same SQL statement again. However, this
  1093. behaviour is disabled when AutoCommit is off: Otherwise the
  1094. transaction state would be completely unpredictable after a
  1095. reconnect.  
  1096.  
  1097. =item *
  1098.  
  1099. The "reconnect" feature of DBD::mysql can be toggled by using the
  1100. L<mysql_auto_reconnect> attribute. This behaviour should be turned off
  1101. in code that uses LOCK TABLE because if the database server time out
  1102. and DBD::mysql reconnect, table locks will be lost without any 
  1103. indication of such loss.
  1104.  
  1105. =back
  1106.  
  1107.  
  1108. =head1 SQL EXTENSIONS
  1109.  
  1110. Certain metadata functions of MySQL that are available on the
  1111. C API level, haven't been implemented here. Instead they are implemented
  1112. as "SQL extensions" because they return in fact nothing else but the
  1113. equivalent of a statement handle. These are:
  1114.  
  1115. =over
  1116.  
  1117. =item LISTFIELDS $table
  1118.  
  1119. Returns a statement handle that describes the columns of $table.
  1120. Ses the docs of mysql_list_fields (C API) for details.
  1121.  
  1122. =back
  1123.  
  1124.  
  1125.  
  1126. =head1 COMPATIBILITY ALERT
  1127.  
  1128. The statement attribute I<TYPE> has changed its meaning, as of
  1129. DBD::mysql 2.0119. Formerly it used to be the an array
  1130. of native engine's column types, but it is now an array of
  1131. portable SQL column types. The old attribute is still available
  1132. as I<mysql_type>.
  1133.  
  1134. DBD::mysql is a moving target, due to a number of reasons:
  1135.  
  1136. =over
  1137.  
  1138. =item -
  1139.  
  1140. Of course we have to conform the DBI guidelines and developments.
  1141.  
  1142. =item -
  1143.  
  1144. We have to keep track with the latest MySQL developments.
  1145.  
  1146. =item -
  1147.  
  1148. And, surprisingly, we have to be as close to ODBC as possible: This is
  1149. due to the current direction of DBI.
  1150.  
  1151. =item -
  1152.  
  1153. And, last not least, as any tool it has a little bit life of its own.
  1154.  
  1155. =back
  1156.  
  1157. This means that a lot of things had to and have to be changed.
  1158. As I am not interested in maintaining a lot of compatibility kludges,
  1159. which only increase the drivers code without being really usefull,
  1160. I did and will remove some features, methods or attributes.
  1161.  
  1162. To ensure a smooth upgrade, the following policy will be applied:
  1163.  
  1164. =over
  1165.  
  1166. =item Obsolete features
  1167.  
  1168. The first step is to declare something obsolete. This means, that no code
  1169. is changed, but the feature appears in the list of obsolete features. See
  1170. L<Obsolete Features> below.
  1171.  
  1172. =item Deprecated features
  1173.  
  1174. If the feature has been obsolete for quite some time, typically in the
  1175. next major stable release, warnings will be inserted in the code. You
  1176. can suppress these warnings by setting
  1177.  
  1178.     $DBD::mysql = 1;
  1179.  
  1180. In the docs the feature will be moved from the list of obsolete features
  1181. to the list of deprecated features. See L<Deprecated Features> below.
  1182.  
  1183. =item Removing features
  1184.  
  1185. Finally features will be removed silently in the next major stable
  1186. release. The feature will be shown in the list of historic features.
  1187. See L<Historic Features> below.
  1188.  
  1189. =back
  1190.  
  1191. Example: The statement handle attribute
  1192.  
  1193.     $sth->{'LENGTH'}
  1194.  
  1195. was declared obsolete in DBD::mysql 2.00xy. It was considered
  1196. deprecated in DBD::mysql 2.02xy and removed in 2.04xy.
  1197.  
  1198.  
  1199. =head2 Obsolete Features
  1200.  
  1201. =over
  1202.  
  1203. =item Database handle attributes
  1204.  
  1205. The following database handle attributes are declared obsolete
  1206. in DBD::mysql 2.09. They will be deprecated in 2.11 and removed
  1207. in 2.13.
  1208.  
  1209. =over
  1210.  
  1211. =item C<$dbh-E<gt>{'errno'}>
  1212.  
  1213. Replaced by C<$dbh-E<gt>{'mysql_errno'}>
  1214.  
  1215. =item C<$dbh-E<gt>{'errmsg'}>
  1216.  
  1217. Replaced by C<$dbh-E<gt>{'mysql_error'}>
  1218.  
  1219. =item C<$dbh-E<gt>{'hostinfo'}>
  1220.  
  1221. Replaced by C<$dbh-E<gt>{'mysql_hostinfo'}>
  1222.  
  1223. =item C<$dbh-E<gt>{'info'}>
  1224.  
  1225. Replaced by C<$dbh-E<gt>{'mysql_info'}>
  1226.  
  1227. =item C<$dbh-E<gt>{'protoinfo'}>
  1228.  
  1229. Replaced by C<$dbh-E<gt>{'mysql_protoinfo'}>
  1230.  
  1231. =item C<$dbh-E<gt>{'serverinfo'}>
  1232.  
  1233. Replaced by C<$dbh-E<gt>{'mysql_serverinfo'}>
  1234.  
  1235. =item C<$dbh-E<gt>{'stats'}>
  1236.  
  1237. Replaced by C<$dbh-E<gt>{'mysql_stat'}>
  1238.  
  1239. =item C<$dbh-E<gt>{'thread_id'}>
  1240.  
  1241. Replaced by C<$dbh-E<gt>{'mysql_thread_id'}>
  1242.  
  1243. =back
  1244.  
  1245. =back
  1246.  
  1247.  
  1248. =head2 Deprecated Features
  1249.  
  1250. =over
  1251.  
  1252. =item _ListTables
  1253.  
  1254. Replace with the standard DBI method C<$dbh-E<gt>tables()>. See also
  1255. C<$dbh-E<gt>table_info()>. Portable applications will prefer
  1256.  
  1257.     @tables = map { $_ =~ s/.*\.//; $_ } $dbh-E<gt>tables()
  1258.  
  1259. because, depending on the engine, the string "user.table" will be
  1260. returned, user being the table owner. The method will be removed
  1261. in DBD::mysql version 2.11xy.
  1262.  
  1263. =back
  1264.  
  1265.  
  1266. =head2 Historic Features
  1267.  
  1268. =over
  1269.  
  1270. =item _CreateDB
  1271.  
  1272. =item _DropDB
  1273.  
  1274. The methods
  1275.  
  1276.     $dbh-E<gt>func($db, '_CreateDB');
  1277.     $dbh-E<gt>func($db, '_DropDB');
  1278.  
  1279. have been used for creating or dropping databases. They have been removed
  1280. in 1.21_07 in favour of
  1281.  
  1282.     $drh-E<gt>func("createdb", $dbname, $host, "admin")
  1283.     $drh-E<gt>func("dropdb", $dbname, $host, "admin")
  1284.  
  1285. =item _ListFields
  1286.  
  1287. The method
  1288.  
  1289.     $sth = $dbh-E<gt>func($table, '_ListFields');
  1290.  
  1291. has been used to list a tables columns names, types and other attributes.
  1292. This method has been removed in 1.21_07 in favour of
  1293.  
  1294.     $sth = $dbh-E<gt>prepare("LISTFIELDS $table");
  1295.  
  1296. =item _ListSelectedFields
  1297.  
  1298. The method
  1299.  
  1300.     $sth->func('_ListSelectedFields');
  1301.  
  1302. use to return a hash ref of attributes like 'IS_NUM', 'IS_KEY' and so
  1303. on. These attributes are now accessible via
  1304.  
  1305.     $sth-E<gt>{'mysql_is_num'};
  1306.     $sth-E<gt>{'mysql_is_key'};
  1307.  
  1308. and so on. Thus the method has been removed in 1.21_07.
  1309.  
  1310. =item _NumRows
  1311.  
  1312. The method
  1313.  
  1314.     $sth-E<gt>func('_NumRows');
  1315.  
  1316. used to be equivalent to
  1317.  
  1318.     $sth-E<gt>rows();
  1319.  
  1320. and has been removed in 1.21_07.
  1321.  
  1322. =item _InsertID
  1323.  
  1324. The method
  1325.  
  1326.     $dbh-E<gt>func('_InsertID');
  1327.  
  1328. used to be equivalent with
  1329.  
  1330.     $dbh-E<gt>{'mysql_insertid'};
  1331.  
  1332. =item Statement handle attributes
  1333.  
  1334. =over
  1335.  
  1336. =item affected_rows
  1337.  
  1338. Replaced with $sth-E<gt>{'mysql_affected_rows'} or the result
  1339. of $sth-E<gt>execute().
  1340.  
  1341. =item format_default_size
  1342.  
  1343. Replaced with $sth-E<gt>{'PRECISION'}.
  1344.  
  1345. =item format_max_size
  1346.  
  1347. Replaced with $sth-E<gt>{'mysql_max_length'}.
  1348.  
  1349. =item format_type_name
  1350.  
  1351. Replaced with $sth-E<gt>{'TYPE'} (portable) or
  1352. $sth-E<gt>{'mysql_type_name'} (MySQL specific).
  1353.  
  1354. =item format_right_justify
  1355.  
  1356. Replaced with $sth-E<gt>->{'TYPE'} (portable) or
  1357. $sth-E<gt>{'mysql_is_num'} (MySQL specific).
  1358.  
  1359. =item insertid
  1360.  
  1361. Replaced with $sth-E<gt>{'mysql_insertid'}.
  1362.  
  1363. =item IS_BLOB
  1364.  
  1365. Replaced with $sth-E<gt>{'TYPE'} (portable) or
  1366. $sth-E<gt>{'mysql_is_blob'} (MySQL specific).
  1367.  
  1368. =item is_blob
  1369.  
  1370. Replaced with $sth-E<gt>{'TYPE'} (portable) or
  1371. $sth-E<gt>{'mysql_is_blob'} (MySQL specific).
  1372.  
  1373. =item IS_PRI_KEY
  1374.  
  1375. Replaced with $sth-E<gt>{'mysql_is_pri_key'}.
  1376.  
  1377. =item is_pri_key
  1378.  
  1379. Replaced with $sth-E<gt>{'mysql_is_pri_key'}.
  1380.  
  1381. =item IS_NOT_NULL
  1382.  
  1383. Replaced with $sth-E<gt>{'NULLABLE'} (do not forget to invert
  1384. the boolean values).
  1385.  
  1386. =item is_not_null
  1387.  
  1388. Replaced with $sth-E<gt>{'NULLABLE'} (do not forget to invert
  1389. the boolean values).
  1390.  
  1391. =item IS_NUM
  1392.  
  1393. Replaced with $sth-E<gt>{'TYPE'} (portable) or
  1394. $sth-E<gt>{'mysql_is_num'} (MySQL specific).
  1395.  
  1396. =item is_num
  1397.  
  1398. Replaced with $sth-E<gt>{'TYPE'} (portable) or
  1399. $sth-E<gt>{'mysql_is_num'} (MySQL specific).
  1400.  
  1401. =item IS_KEY
  1402.  
  1403. Replaced with $sth-E<gt>{'mysql_is_key'}.
  1404.  
  1405. =item is_key
  1406.  
  1407. Replaced with $sth-E<gt>{'mysql_is_key'}.
  1408.  
  1409. =item MAXLENGTH
  1410.  
  1411. Replaced with $sth-E<gt>{'mysql_max_length'}.
  1412.  
  1413. =item maxlength
  1414.  
  1415. Replaced with $sth-E<gt>{'mysql_max_length'}.
  1416.  
  1417. =item LENGTH
  1418.  
  1419. Replaced with $sth-E<gt>{'PRECISION'} (portable) or
  1420. $sth-E<gt>{'mysql_length'} (MySQL specific)
  1421.  
  1422. =item length
  1423.  
  1424. Replaced with $sth-E<gt>{'PRECISION'} (portable) or
  1425. $sth-E<gt>{'mysql_length'} (MySQL specific)
  1426.  
  1427. =item NUMFIELDS
  1428.  
  1429. Replaced with $sth-E<gt>{'NUM_OF_FIELDS'}.
  1430.  
  1431. =item numfields
  1432.  
  1433. Replaced with $sth-E<gt>{'NUM_OF_FIELDS'}.
  1434.  
  1435. =item NUMROWS
  1436.  
  1437. Replaced with the result of $sth-E<gt>execute() or
  1438. $sth-E<gt>{'mysql_affected_rows'}.
  1439.  
  1440. =item TABLE
  1441.  
  1442. Replaced with $sth-E<gt>{'mysql_table'}.
  1443.  
  1444. =item table
  1445.  
  1446. Replaced with $sth-E<gt>{'mysql_table'}.
  1447.  
  1448. =back
  1449.  
  1450. =back
  1451.  
  1452.  
  1453. =head1 MULTITHREADING
  1454.  
  1455. The multithreading capabilities of DBD::mysql depend completely
  1456. on the underlying C libraries: The modules are working with handle data
  1457. only, no global variables are accessed or (to the best of my knowledge)
  1458. thread unsafe functions are called. Thus DBD::mysql is believed
  1459. to be completely thread safe, if the C libraries are thread safe
  1460. and you don't share handles among threads.
  1461.  
  1462. The obvious question is: Are the C libraries thread safe?
  1463. In the case of MySQL the answer is "mostly" and, in theory, you should
  1464. be able to get a "yes", if the C library is compiled for being thread
  1465. safe (By default it isn't.) by passing the option -with-thread-safe-client
  1466. to configure. See the section on I<How to make a threadsafe client> in
  1467. the manual.
  1468.  
  1469.  
  1470. =head1 INSTALLATION
  1471.  
  1472. Windows users may skip this section and pass over to L<WIN32
  1473. INSTALLATION> below. Others, go on reading.
  1474.  
  1475. First of all, you do not need an installed MySQL server for installing
  1476. DBD::mysql. However, you need at least the client
  1477. libraries and possibly the header files, if you are compiling DBD::mysql
  1478. from source. In the case of MySQL you can create a
  1479. client-only version by using the configure option --without-server.
  1480. If you are using precompiled binaries, then it may be possible to
  1481. use just selected RPM's like MySQL-client and MySQL-devel or something
  1482. similar, depending on the distribution.
  1483.  
  1484. First you need to install the DBI module. For using I<dbimon>, a
  1485. simple DBI shell it is recommended to install Data::ShowTable another
  1486. Perl module.
  1487.  
  1488. I recommend trying automatic installation via the CPAN module. Try
  1489.  
  1490.   perl -MCPAN -e shell
  1491.  
  1492. If you are using the CPAN module for the first time, it will prompt
  1493. you a lot of questions. If you finally receive the CPAN prompt, enter
  1494.  
  1495.   install Bundle::DBD::mysql
  1496.  
  1497. If this fails (which may be the case for a number of reasons, for
  1498. example because you are behind a firewall or don't have network
  1499. access), you need to do a manual installation. First of all you
  1500. need to fetch the archives from any CPAN mirror, for example
  1501.  
  1502.   ftp://ftp.funet.fi/pub/languages/perl/CPAN/modules/by-module
  1503.  
  1504. The following archives are required (version numbers may have
  1505. changed, I choose those which are current as of this writing):
  1506.  
  1507.   DBI/DBI-1.15.tar.gz
  1508.   Data/Data-ShowTable-3.3.tar.gz
  1509.   DBD/DBD-mysql-2.1001.tar.gz
  1510.  
  1511. Then enter the following commands:
  1512.  
  1513.   gzip -cd DBI-1.15.tar.gz | tar xf -
  1514.   cd DBI-1.15
  1515.   perl Makefile.PL
  1516.   make
  1517.   make test
  1518.   make install
  1519.  
  1520.   cd ..
  1521.   gzip -cd Data-ShowTable-3.3.tar.gz | tar xf -
  1522.   cd Data-ShowTable-3.3
  1523.   perl Makefile.PL
  1524.   make
  1525.   make install  # Don't try make test, the test suite is broken
  1526.  
  1527.   cd ..
  1528.   gzip -cd DBD-mysql-2.1001.tar.gz | tar xf -
  1529.   cd DBD-mysql-2.1001
  1530.   perl Makefile.PL
  1531.   make
  1532.   make test
  1533.   make install
  1534.  
  1535. During "perl Makefile.PL" you will be prompted some questions.
  1536. Other questions are the directories with header files and libraries.
  1537. For example, of your file F<mysql.h> is in F</usr/include/mysql/mysql.h>,
  1538. then enter the header directory F</usr>, likewise for
  1539. F</usr/lib/mysql/libmysqlclient.a> or F</usr/lib/libmysqlclient.so>.
  1540.  
  1541.  
  1542. =head1 WIN32 INSTALLATION
  1543.  
  1544. If you are using ActivePerl, you may use ppm to install DBD-mysql.
  1545. For Perl 5.6, upgrade to Build 623 or later, then it is sufficient
  1546. to run
  1547.  
  1548.   ppm install DBI
  1549.   ppm install DBD::mysql
  1550.  
  1551. If you need an HTTP proxy, you might need to set the environment
  1552. variable http_proxy, for example like this:
  1553.  
  1554.   set http_proxy=http://myproxy.com:8080/
  1555.  
  1556. As of this writing, DBD::mysql is missing in the ActivePerl 5.8.0
  1557. repository. However, Randy Kobes has kindly donated an own
  1558. distribution and the following might succeed:
  1559.  
  1560.   ppm install http://theoryx5.uwinnipeg.ca/ppms/DBD-mysql.ppd
  1561.  
  1562. Otherwise you definitely *need* a C compiler. And it *must* be the same
  1563. compiler that was being used for compiling Perl itself. If you don't
  1564. have a C compiler, the file README.win32 from the Perl source
  1565. distribution tells you where to obtain freely distributable C compilers
  1566. like egcs or gcc. The Perl sources are available on any CPAN mirror in
  1567. the src directory, for example
  1568.  
  1569.     ftp://ftp.funet.fi/pub/languages/perl/CPAN/src/latest.tar.gz
  1570.  
  1571. I recommend using the win32clients package for installing DBD::mysql
  1572. under Win32, available for download on www.tcx.se. The following steps
  1573. have been required for me:
  1574.  
  1575. =over
  1576.  
  1577. =item -
  1578.  
  1579. The current Perl versions (5.6, as of this writing) do have a problem
  1580. with detecting the C libraries. I recommend to apply the following
  1581. patch:
  1582.  
  1583.   *** c:\Perl\lib\ExtUtils\Liblist.pm.orig Sat Apr 15 20:03:40 2000
  1584.   --- c:\Perl\lib\ExtUtils\Liblist.pm      Sat Apr 15 20:03:45 2000
  1585.   ***************
  1586.   *** 230,235 ****
  1587.   --- 230,239 ----
  1588.       # add "$Config{installarchlib}/CORE" to default search path
  1589.       push @libpath, "$Config{installarchlib}/CORE";
  1590.  
  1591.   +     if ($VC  and  exists($ENV{LIB})  and  defined($ENV{LIB})) {
  1592.   +       push(@libpath, split(/;/, $ENV{LIB}));
  1593.   +     }
  1594.   +
  1595.       foreach (Text::ParseWords::quotewords('\s+', 0, $potential_libs)){
  1596.  
  1597.         $thislib = $_;
  1598.                                                                        
  1599. =item -
  1600.  
  1601. Extract sources into F<C:\>. This will create a directory F<C:\mysql>
  1602. with subdirectories include and lib.
  1603.  
  1604. IMPORTANT: Make sure this subdirectory is not shared by other TCX
  1605. files! In particular do *not* store the MySQL server in the same
  1606. directory. If the server is already installed in F<C:\mysql>,
  1607. choose a location like F<C:\tmp>, extract the win32clients there.
  1608. Note that you can remove this directory entirely once you have
  1609. installed DBD::mysql.
  1610.  
  1611. =item -
  1612.  
  1613. Extract the DBD::mysql sources into another directory, for
  1614. example F<C:\src\siteperl>
  1615.  
  1616. =item -
  1617.  
  1618. Open a DOS shell and change directory to F<C:\src\siteperl>.
  1619.  
  1620. =item -
  1621.  
  1622. The next step is only required if you repeat building the modules: Make
  1623. sure that you have a clean build tree by running
  1624.  
  1625.   nmake realclean
  1626.  
  1627. If you don't have VC++, replace nmake with your flavour of make. If
  1628. error messages are reported in this step, you may safely ignore them.
  1629.  
  1630. =item -
  1631.  
  1632. Run
  1633.  
  1634.   perl Makefile.PL
  1635.  
  1636. which will prompt you for some settings. The really important ones are:
  1637.  
  1638.   Which DBMS do you want to use?
  1639.  
  1640. enter a 1 here (MySQL only), and
  1641.  
  1642.   Where is your mysql installed? Please tell me the directory that
  1643.   contains the subdir include.
  1644.  
  1645. where you have to enter the win32clients directory, for example
  1646. F<C:\mysql> or F<C:\tmp\mysql>.
  1647.  
  1648. =item -
  1649.  
  1650. Continued in the usual way:
  1651.  
  1652.   nmake
  1653.   nmake install
  1654.  
  1655. =back
  1656.  
  1657. If you want to create a PPM package for the ActiveState Perl version, then
  1658. modify the above steps as follows: Run
  1659.  
  1660.   perl Makefile.PL NAME=DBD-mysql BINARY_LOCATION=DBD-mysql.tar.gz
  1661.   nmake ppd
  1662.   nmake
  1663.  
  1664. Once that is done, use tar and gzip (for example those from the CygWin32
  1665. distribution) to create an archive:
  1666.  
  1667.   mkdir x86
  1668.   tar cf x86/DBD-mysql.tar blib
  1669.   gzip x86/DBD-mysql.tar
  1670.  
  1671. Put the files x86/DBD-mysql.tar.gz and DBD-mysql.ppd onto some WWW server
  1672. and install them by typing
  1673.  
  1674.   install http://your.server.name/your/directory/DBD-mysql.ppd
  1675.  
  1676. in the PPM program.
  1677.  
  1678.  
  1679. =head1 AUTHORS
  1680.  
  1681. The current version of B<DBD::mysql> is almost completely written
  1682. by Jochen Wiedmann, and is now being maintained by
  1683. Rudy Lippan (I<rlippan@remotelinux.com>). The first version's author
  1684. was Alligator Descartes (I<descarte@symbolstone.org>), who has been
  1685. aided and abetted by Gary Shea, Andreas K÷nig and Tim Bunce
  1686. amongst others.
  1687.  
  1688. The B<Mysql> module was originally written by Andreas K÷nig
  1689. <koenig@kulturbox.de>. The current version, mainly an emulation
  1690. layer, is from Jochen Wiedmann.
  1691.  
  1692.  
  1693. =head1 COPYRIGHT
  1694.  
  1695.  
  1696. This module is Copyright (c) 2003 Rudolf Lippan; Large Portions 
  1697. Copyright (c) 1997-2003 Jochen Wiedmann, with code portions 
  1698. Copyright (c)1994-1997 their original authors This module is
  1699. released under the same license as Perl itself. See the Perl README
  1700. for details.
  1701.  
  1702.  
  1703. =head1 MAILING LIST SUPPORT
  1704.  
  1705. This module is maintained and supported on a mailing list,
  1706.  
  1707.     perl@lists.mysql.com
  1708.  
  1709. To subscribe to this list, send a mail to
  1710.  
  1711.     perl-subscribe@lists.mysql.com
  1712.  
  1713. or
  1714.  
  1715.     perl-digest-subscribe@lists.mysql.com
  1716.  
  1717. Mailing list archives are available at
  1718.  
  1719.     http://www.progressive-comp.com/Lists/?l=msql-mysql-modules
  1720.  
  1721.  
  1722. Additionally you might try the dbi-user mailing list for questions about
  1723. DBI and its modules in general. Subscribe via
  1724.  
  1725.     http://www.fugue.com/dbi
  1726.  
  1727. Mailing list archives are at
  1728.  
  1729.      http://www.rosat.mpe-garching.mpg.de/mailing-lists/PerlDB-Interest/
  1730.      http://outside.organic.com/mail-archives/dbi-users/
  1731.      http://www.coe.missouri.edu/~faq/lists/dbi.html
  1732.  
  1733.  
  1734. =head1 ADDITIONAL DBI INFORMATION
  1735.  
  1736. Additional information on the DBI project can be found on the World
  1737. Wide Web at the following URL:
  1738.  
  1739.     http://www.symbolstone.org/technology/perl/DBI
  1740.  
  1741. where documentation, pointers to the mailing lists and mailing list
  1742. archives and pointers to the most current versions of the modules can
  1743. be used.
  1744.  
  1745. Information on the DBI interface itself can be gained by typing:
  1746.  
  1747.     perldoc DBI
  1748.  
  1749. right now!
  1750.  
  1751. =cut
  1752.  
  1753.  
  1754.