Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man3 / DBI.3
.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "DBI 3"
.TH DBI 3 "2002-10-01" "perl v5.8.0" "User Contributed Perl Documentation"
.SH "NAME"
DBI \- Database independent interface for Perl
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 1
\& use DBI;
.Ve
.PP
.Vb 2
\& @driver_names = DBI->available_drivers;
\& @data_sources = DBI->data_sources($driver_name, \e%attr);
.Ve
.PP
.Vb 1
\& $dbh = DBI->connect($data_source, $username, $auth, \e%attr);
.Ve
.PP
.Vb 3
\& $rv = $dbh->do($statement);
\& $rv = $dbh->do($statement, \e%attr);
\& $rv = $dbh->do($statement, \e%attr, @bind_values);
.Ve
.PP
.Vb 2
\& $ary_ref = $dbh->selectall_arrayref($statement);
\& $ary_ref = $dbh->selectall_hashref($statement);
.Ve
.PP
.Vb 1
\& $ary_ref = $dbh->selectcol_arrayref($statement);
.Ve
.PP
.Vb 2
\& $ary_ref = $dbh->selectrow_arrayref($statement);
\& @row_ary = $dbh->selectrow_array($statement);
.Ve
.PP
.Vb 2
\& $sth = $dbh->prepare($statement);
\& $sth = $dbh->prepare_cached($statement);
.Ve
.PP
.Vb 3
\& $rv = $sth->bind_param($p_num, $bind_value);
\& $rv = $sth->bind_param($p_num, $bind_value, $bind_type);
\& $rv = $sth->bind_param($p_num, $bind_value, \e%attr);
.Ve
.PP
.Vb 2
\& $rv = $sth->execute;
\& $rv = $sth->execute(@bind_values);
.Ve
.PP
.Vb 2
\& $rc = $sth->bind_col($col_num, \e$col_variable);
\& $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
.Ve
.PP
.Vb 3
\& @row_ary = $sth->fetchrow_array;
\& $ary_ref = $sth->fetchrow_arrayref;
\& $hash_ref = $sth->fetchrow_hashref;
.Ve
.PP
.Vb 1
\& $ary_ref = $sth->fetchall_arrayref;
.Ve
.PP
.Vb 1
\& $rv = $sth->rows;
.Ve
.PP
.Vb 2
\& $rc = $dbh->commit;
\& $rc = $dbh->rollback;
.Ve
.PP
.Vb 1
\& $sql = $dbh->quote($string);
.Ve
.PP
.Vb 3
\& $rc = $h->err;
\& $str = $h->errstr;
\& $rv = $h->state;
.Ve
.PP
.Vb 1
\& $rc = $dbh->disconnect;
.Ve
.PP
\&\fIThis synopsis above only lists the major methods.\fR
.Sh "\s-1GETTING\s0 \s-1HELP\s0"
.IX Subsection "GETTING HELP"
If you have questions about \s-1DBI\s0, you can get help from
the \fIdbi\-users@perl.org\fR mailing list.
You can subscribe to the list by emailing:
.PP
.Vb 1
\& dbi-users-help@perl.org
.Ve
.PP
Also worth a visit is the \s-1DBI\s0 home page at:
.PP
.Vb 1
\& http://dbi.perl.org/
.Ve
.PP
Before asking any questions, reread this document, consult the
archives and read the \s-1DBI\s0 \s-1FAQ\s0. The archives are listed
at the end of this document.
The \s-1FAQ\s0 is installed as a \s-1DBI::FAQ\s0 module so
you can read it by executing \f(CW\*(C`perldoc DBI::FAQ\*(C'\fR.
.PP
Please note that Tim Bunce does not maintain the mailing lists or the
web page (generous volunteers do that). So please don't send mail
directly to him; he just doesn't have the time to answer questions
personally. The \fIdbi-users\fR mailing list has lots of experienced
people who should be able to help you if you need it.
.Sh "\s-1NOTE\s0"
.IX Subsection "NOTE"
This is the \s-1DBI\s0 specification that corresponds to the \s-1DBI\s0 version 1.17
(\f(CW\*(C`$Date: 2001/06/04 17:20:21 $\*(C'\fR).
.PP
The \s-1DBI\s0 specification is evolving at a steady pace, so it's
important to check that you have the latest copy. The \s-1RECENT\s0 \s-1CHANGES\s0
section below has a summary of user-visible changes. The \fIChanges\fR
file supplied with the \s-1DBI\s0 holds more detailed change information.
.PP
Note also that whenever the \s-1DBI\s0 changes, the drivers take some time to
catch up. Recent versions of the \s-1DBI\s0 have added new features
(marked \fI\s-1NEW\s0\fR in the text) that may not yet be supported by the drivers
you use. Talk to the authors of those drivers if you need the features.
.PP
Extensions to the \s-1DBI\s0 and other \s-1DBI\s0 related modules use the \f(CW\*(C`DBIx::*\*(C'\fR
namespace. See \*(L"Naming Conventions and Name Space\*(R" and:
.PP
.Vb 1
\& http://www.perl.com/CPAN/modules/by-module/DBIx/
.Ve
.Sh "\s-1RECENT\s0 \s-1CHANGES\s0"
.IX Subsection "RECENT CHANGES"
Here is a brief summary of significant user-visible changes in recent versions.
(If a recent version isn't mentioned, it simply means that there were no
significant user-visible changes in that version.)
.IP "\s-1DBI\s0 1.15" 4
.IX Item "DBI 1.15"
Added selectall_hashref, selectrow_hashref, selectrow_arrayref methods.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
The \s-1DBI\s0 is a database access module for the Perl programming language. It defines
a set of methods, variables, and conventions that provide a consistent
database interface, independent of the actual database being used.
.PP
It is important to remember that the \s-1DBI\s0 is just an interface.
The \s-1DBI\s0 is a layer
of \*(L"glue\*(R" between an application and one or more database \fIdriver\fR
modules. It is the driver modules which do most of the real work. The \s-1DBI\s0
provides a standard interface and framework for the drivers to operate
within.
.Sh "Architecture of a \s-1DBI\s0 Application"
.IX Subsection "Architecture of a DBI Application"
.Vb 11
\& |<- Scope of DBI ->|
\& .-. .--------------. .-------------.
\& .-------. | |---| XYZ Driver |---| XYZ Engine |
\& | Perl | | | `--------------' `-------------'
\& | script| |A| |D| .--------------. .-------------.
\& | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
\& | DBI | |I| |I| `--------------' `-------------'
\& | API | | |...
\& |methods| | |... Other drivers
\& `-------' | |...
\& `-'
.Ve
.PP
The \s-1API\s0, or Application Programming Interface, defines the
call interface and variables for Perl scripts to use. The \s-1API\s0
is implemented by the Perl \s-1DBI\s0 extension.
.PP
The \s-1DBI\s0 \*(L"dispatches\*(R" the method calls to the appropriate driver for
actual execution. The \s-1DBI\s0 is also responsible for the dynamic loading
of drivers, error checking and handling, providing default
implementations for methods, and many other non-database specific duties.
.PP
Each driver
contains implementations of the \s-1DBI\s0 methods using the
private interface functions of the corresponding database engine. Only authors
of sophisticated/multi\-database applications or generic library
functions need be concerned with drivers.
.Sh "Notation and Conventions"
.IX Subsection "Notation and Conventions"
The following conventions are used in this document:
.PP
.Vb 11
\& $dbh Database handle object
\& $sth Statement handle object
\& $drh Driver handle object (rarely seen or used in applications)
\& $h Any of the handle types above ($dbh, $sth, or $drh)
\& $rc General Return Code (boolean: true=ok, false=error)
\& $rv General Return Value (typically an integer)
\& @ary List of values returned from the database, typically a row of data
\& $rows Number of rows processed (if available, else -1)
\& $fh A filehandle
\& undef NULL values are represented by undefined values in Perl
\& \e%attr Reference to a hash of attribute values passed to methods
.Ve
.PP
Note that Perl will automatically destroy database and statement handle objects
if all references to them are deleted.
.Sh "Outline Usage"
.IX Subsection "Outline Usage"
To use \s-1DBI\s0,
first you need to load the \s-1DBI\s0 module:
.PP
.Vb 2
\& use DBI;
\& use strict;
.Ve
.PP
(The \f(CW\*(C`use strict;\*(C'\fR isn't required but is strongly recommended.)
.PP
Then you need to \*(L"connect\*(R" to your data source and get a \fIhandle\fR for that
connection:
.PP
.Vb 2
\& $dbh = DBI->connect($dsn, $user, $password,
\& { RaiseError => 1, AutoCommit => 0 });
.Ve
.PP
Since connecting can be expensive, you generally just connect at the
start of your program and disconnect at the end.
.PP
Explicitly defining the required \f(CW\*(C`AutoCommit\*(C'\fR behavior is strongly
recommended and may become mandatory in a later version. This
determines whether changes are automatically committed to the
database when executed, or need to be explicitly committed later.
.PP
The \s-1DBI\s0 allows an application to \*(L"prepare\*(R" statements for later
execution. A prepared statement is identified by a statement handle
held in a Perl variable.
We'll call the Perl variable \f(CW$sth\fR in our examples.
.PP
The typical method call sequence for a \f(CW\*(C`SELECT\*(C'\fR statement is:
.PP
.Vb 4
\& prepare,
\& execute, fetch, fetch, ...
\& execute, fetch, fetch, ...
\& execute, fetch, fetch, ...
.Ve
.PP
for example:
.PP
.Vb 1
\& $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
.Ve
.PP
.Vb 1
\& $sth->execute( $baz );
.Ve
.PP
.Vb 3
\& while ( @row = $sth->fetchrow_array ) {
\& print "@row\en";
\& }
.Ve
.PP
The typical method call sequence for a \fInon\fR\-\f(CW\*(C`SELECT\*(C'\fR statement is:
.PP
.Vb 4
\& prepare,
\& execute,
\& execute,
\& execute.
.Ve
.PP
for example:
.PP
.Vb 1
\& $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
.Ve
.PP
.Vb 5
\& while(<CSV>) {
\& chomp;
\& my ($foo,$bar,$baz) = split /,/;
\& $sth->execute( $foo, $bar, $baz );
\& }
.Ve
.PP
The \f(CW\*(C`do()\*(C'\fR method can be used for non repeated \fInon\fR\-\f(CW\*(C`SELECT\*(C'\fR statement
(or with drivers that don't support placeholders):
.PP
.Vb 1
\& $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
.Ve
.PP
To commit your changes to the database (when \*(L"AutoCommit\*(R" is off):
.PP
.Vb 1
\& $dbh->commit; # or call $dbh->rollback; to undo changes
.Ve
.PP
Finally, when you have finished working with the data source, you should
\&\*(L"disconnect\*(R" from it:
.PP
.Vb 1
\& $dbh->disconnect;
.Ve
.Sh "General Interface Rules & Caveats"
.IX Subsection "General Interface Rules & Caveats"
The \s-1DBI\s0 does not have a concept of a \*(L"current session\*(R". Every session
has a handle object (i.e., a \f(CW$dbh\fR) returned from the \f(CW\*(C`connect\*(C'\fR method.
That handle object is used to invoke database related methods.
.PP
Most data is returned to the Perl script as strings. (Null values are
returned as \f(CW\*(C`undef\*(C'\fR.) This allows arbitrary precision numeric data to be
handled without loss of accuracy. Beware that Perl may not preserve
the same accuracy when the string is used as a number.
.PP
Dates and times are returned as character strings in the current
default format of the corresponding database engine. Time zone effects
are database/driver dependent.
.PP
Perl supports binary data in Perl strings, and the \s-1DBI\s0 will pass binary
data to and from the driver without change. It is up to the driver
implementors to decide how they wish to handle such binary data.
.PP
Most databases that understand multiple character sets have a
default global charset. Text stored in the database is, or should
be, stored in that charset; if not, then that's the fault of either
the database or the application that inserted the data. When text is
fetched it should be automatically converted to the charset of the
client, presumably based on the locale. If a driver needs to set a
flag to get that behavior, then it should do so; it should not require
the application to do that.
.PP
Multiple \s-1SQL\s0 statements may not be combined in a single statement
handle (\f(CW$sth\fR), although some databases and drivers do support this
(notably Sybase and \s-1SQL\s0 Server).
.PP
Non-sequential record reads are not supported in this version of the \s-1DBI\s0.
In other words, records can only be fetched in the order that the
database returned them, and once fetched they are forgotten.
.PP
Positioned updates and deletes are not directly supported by the \s-1DBI\s0.
See the description of the \f(CW\*(C`CursorName\*(C'\fR attribute for an alternative.
.PP
Individual driver implementors are free to provide any private
functions and/or handle attributes that they feel are useful.
Private driver functions can be invoked using the \s-1DBI\s0 \f(CW\*(C`func()\*(C'\fR method.
Private driver attributes are accessed just like standard attributes.
.PP
Many methods have an optional \f(CW\*(C`\e%attr\*(C'\fR parameter which can be used to
pass information to the driver implementing the method. Except where
specifically documented, the \f(CW\*(C`\e%attr\*(C'\fR parameter can only be used to pass
driver specific hints. In general, you can ignore \f(CW\*(C`\e%attr\*(C'\fR parameters
or pass it as \f(CW\*(C`undef\*(C'\fR.
.Sh "Naming Conventions and Name Space"
.IX Subsection "Naming Conventions and Name Space"
The \s-1DBI\s0 package and all packages below it (\f(CW\*(C`DBI::*\*(C'\fR) are reserved for
use by the \s-1DBI\s0. Extensions and related modules use the \f(CW\*(C`DBIx::\*(C'\fR
namespace (see \f(CW\*(C`http://www.perl.com/CPAN/modules/by\-module/DBIx/\*(C'\fR).
Package names beginning with \f(CW\*(C`DBD::\*(C'\fR are reserved for use
by \s-1DBI\s0 database drivers. All environment variables used by the \s-1DBI\s0
or by individual DBDs begin with "\f(CW\*(C`DBI_\*(C'\fR\*(L" or \*(R"\f(CW\*(C`DBD_\*(C'\fR".
.PP
The letter case used for attribute names is significant and plays an
important part in the portability of \s-1DBI\s0 scripts. The case of the
attribute name is used to signify who defined the meaning of that name
and its values.
.PP
.Vb 5
\& Case of name Has a meaning defined by
\& ------------ ------------------------
\& UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable)
\& MixedCase DBI API (portable), underscores are not used.
\& lower_case Driver or database engine specific (non-portable)
.Ve
.PP
It is of the utmost importance that Driver developers only use
lowercase attribute names when defining private attributes. Private
attribute names must be prefixed with the driver name or suitable
abbreviation (e.g., "\f(CW\*(C`ora_\*(C'\fR\*(L" for Oracle, \*(R"\f(CW\*(C`ing_\*(C'\fR" for Ingres, etc).
.PP
Driver Specific Prefix Registry:
.PP
.Vb 24
\& ad_ DBD::AnyData
\& ado_ DBD::ADO
\& best_ DBD::BestWins
\& csv_ DBD::CSV
\& db2_ DBD::DB2
\& f_ DBD::File
\& file_ DBD::TextFile
\& ib_ DBD::InterBase
\& ing_ DBD::Ingres
\& ix_ DBD::Informix
\& msql_ DBD::mSQL
\& mysql_ DBD::mysql
\& odbc_ DBD::ODBC
\& ora_ DBD::Oracle
\& pg_ DBD::Pg
\& proxy_ DBD::Proxy
\& rdb_ DBD::RDB
\& sapdb_ DBD::SAP_DB
\& solid_ DBD::Solid
\& syb_ DBD::Sybase
\& tdat_ DBD::Teradata
\& tuber_ DBD::Tuber
\& uni_ DBD::Unify
\& xbase_ DBD::XBase
.Ve
.Sh "\s-1SQL\s0 \- A Query Language"
.IX Subsection "SQL - A Query Language"
Most \s-1DBI\s0 drivers require applications to use a dialect of \s-1SQL\s0
(Structured Query Language) to interact with the database engine.
The following links provide useful information and further links about
\&\s-1SQL:\s0
.PP
.Vb 3
\& http://www.altavista.com/query?q=sql+tutorial
\& http://www.jcc.com/sql_stnd.html
\& http://www.contrib.andrew.cmu.edu/~shadow/sql.html
.Ve
.PP
The \s-1DBI\s0 itself does not mandate or require any particular language to
be used; it is language independent. In \s-1ODBC\s0 terms, the \s-1DBI\s0 is in
\&\*(L"pass\-thru\*(R" mode, although individual drivers might not be. The only requirement
is that queries and other statements must be expressed as a single
string of characters passed as the first argument to the \*(L"prepare\*(R" or
\&\*(L"do\*(R" methods.
.PP
For an interesting diversion on the \fIreal\fR history of \s-1RDBMS\s0 and \s-1SQL\s0,
from the people who made it happen, see:
.PP
.Vb 1
\& http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
.Ve
.PP
Follow the \*(L"And the rest\*(R" and \*(L"Intergalactic dataspeak\*(R" links for the
\&\s-1SQL\s0 history.
.Sh "Placeholders and Bind Values"
.IX Subsection "Placeholders and Bind Values"
Some drivers support placeholders and bind values.
\&\fIPlaceholders\fR, also called parameter markers, are used to indicate
values in a database statement that will be supplied later,
before the prepared statement is executed. For example, an application
might use the following to insert a row of data into the \s-1SALES\s0 table:
.PP
.Vb 1
\& INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
.Ve
.PP
or the following, to select the description for a product:
.PP
.Vb 1
\& SELECT description FROM products WHERE product_code = ?
.Ve
.PP
The \f(CW\*(C`?\*(C'\fR characters are the placeholders. The association of actual
values with placeholders is known as \fIbinding\fR, and the values are
referred to as \fIbind values\fR.
.PP
When using placeholders with the \s-1SQL\s0 \f(CW\*(C`LIKE\*(C'\fR qualifier, you must
remember that the placeholder substitutes for the whole string.
So you should use "\f(CW\*(C`... LIKE ? ...\*(C'\fR" and include any wildcard
characters in the value that you bind to the placeholder.
.PP
\&\fBNull Values\fR
.PP
Undefined values, or \f(CW\*(C`undef\*(C'\fR, can be used to indicate null values.
However, care must be taken in the particular case of trying to use
null values to qualify a \f(CW\*(C`SELECT\*(C'\fR statement. Consider:
.PP
.Vb 1
\& SELECT description FROM products WHERE product_code = ?
.Ve
.PP
Binding an \f(CW\*(C`undef\*(C'\fR (\s-1NULL\s0) to the placeholder will \fInot\fR select rows
which have a \s-1NULL\s0 \f(CW\*(C`product_code\*(C'\fR! Refer to the \s-1SQL\s0 manual for your database
engine or any \s-1SQL\s0 book for the reasons for this. To explicitly select
NULLs you have to say "\f(CW\*(C`WHERE product_code IS NULL\*(C'\fR" and to make that
general you have to say:
.PP
.Vb 1
\& ... WHERE (product_code = ? OR (? IS NULL AND product_code IS NULL))
.Ve
.PP
and bind the same value to both placeholders.
.PP
\&\fBPerformance\fR
.PP
Without using placeholders, the insert statement shown previously would have to
contain the literal values to be inserted and would have to be
re-prepared and re-executed for each row. With placeholders, the insert
statement only needs to be prepared once. The bind values for each row
can be given to the \f(CW\*(C`execute\*(C'\fR method each time it's called. By avoiding
the need to re-prepare the statement for each row, the application
typically runs many times faster. Here's an example:
.PP
.Vb 9
\& my $sth = $dbh->prepare(q{
\& INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
\& }) or die $dbh->errstr;
\& while (<>) {
\& chomp;
\& my ($product_code, $qty, $price) = split /,/;
\& $sth->execute($product_code, $qty, $price) or die $dbh->errstr;
\& }
\& $dbh->commit or die $dbh->errstr;
.Ve
.PP
See \*(L"execute\*(R" and \*(L"bind_param\*(R" for more details.
.PP
The \f(CW\*(C`q{...}\*(C'\fR style quoting used in this example avoids clashing with
quotes that may be used in the \s-1SQL\s0 statement. Use the double-quote like
\&\f(CW\*(C`qq{...}\*(C'\fR operator if you want to interpolate variables into the string.
See \*(L"Quote and Quote-like Operators\*(R" in perlop for more details.
.PP
See also the \*(L"bind_column\*(R" method, which is used to associate Perl
variables with the output columns of a \f(CW\*(C`SELECT\*(C'\fR statement.
.SH "THE DBI PACKAGE AND CLASS"
.IX Header "THE DBI PACKAGE AND CLASS"
In this section, we cover the \s-1DBI\s0 class methods, utility functions,
and the dynamic attributes associated with generic \s-1DBI\s0 handles.
.Sh "\s-1DBI\s0 Constants"
.IX Subsection "DBI Constants"
The following \s-1SQL\s0 standard type constants can be imported individually
or, by importing the special \f(CW\*(C`:sql_types\*(C'\fR tag, all together:
.PP
.Vb 8
\& SQL_CHAR SQL_NUMERIC SQL_DECIMAL SQL_INTEGER SQL_SMALLINT
\& SQL_FLOAT SQL_REAL SQL_DOUBLE SQL_VARCHAR
\& SQL_DATE SQL_TIME SQL_TIMESTAMP
\& SQL_LONGVARCHAR SQL_BINARY SQL_VARBINARY SQL_LONGVARBINARY
\& SQL_BIGINT SQL_TINYINT
\& SQL_WCHAR SQL_WVARCHAR SQL_WLONGVARCHAR
\& SQL_BIT
\& SQL_ALL_TYPES
.Ve
.PP
See the \*(L"type_info\*(R", \*(L"type_info_all\*(R", and \*(L"bind_param\*(R" methods
for possible uses.
.Sh "\s-1DBI\s0 Class Methods"
.IX Subsection "DBI Class Methods"
The following methods are provided by the \s-1DBI\s0 class:
.ie n .IP """connect""" 4
.el .IP "\f(CWconnect\fR" 4
.IX Item "connect"
.Vb 4
\& $dbh = DBI->connect($data_source, $username, $password)
\& or die $DBI::errstr;
\& $dbh = DBI->connect($data_source, $username, $password, \e%attr)
\& or die $DBI::errstr;
.Ve
.Sp
Establishes a database connection, or session, to the requested \f(CW$data_source\fR.
Returns a database handle object if the connection succeeds. Use
\&\f(CW\*(C`$dbh\-\*(C'\fR>\f(CW\*(C`disconnect\*(C'\fR to terminate the connection.
.Sp
If the connect fails (see below), it returns \f(CW\*(C`undef\*(C'\fR and sets both \f(CW$DBI::err\fR
and \f(CW$DBI::errstr\fR. (It does \fInot\fR set \f(CW$!\fR, etc.) You should generally
test the return status of \f(CW\*(C`connect\*(C'\fR and \f(CW\*(C`print $DBI::errstr\*(C'\fR if it has failed.
.Sp
Multiple simultaneous connections to multiple databases through multiple
drivers can be made via the \s-1DBI\s0. Simply make one \f(CW\*(C`connect\*(C'\fR call for each
database and keep a copy of each returned database handle.
.Sp
The \f(CW$data_source\fR value should begin with "\f(CW\*(C`dbi:\*(C'\fR\fIdriver_name\fR\f(CW\*(C`:\*(C'\fR". The
\&\fIdriver_name\fR specifies the driver that will be used to make the
connection. (Letter case is significant.)
.Sp
As a convenience, if the \f(CW$data_source\fR parameter is undefined or empty, the
\&\s-1DBI\s0 will substitute the value of the environment variable \f(CW\*(C`DBI_DSN\*(C'\fR.
If just the \fIdriver_name\fR part is empty (i.e., the \f(CW$data_source\fR prefix is "\f(CW\*(C`dbi::\*(C'\fR"),
the environment variable \f(CW\*(C`DBI_DRIVER\*(C'\fR is used. If neither variable is set,
then \f(CW\*(C`connect\*(C'\fR dies.
.Sp
Examples of \f(CW$data_source\fR values are:
.Sp
.Vb 3
\& dbi:DriverName:database_name
\& dbi:DriverName:database_name@hostname:port
\& dbi:DriverName:database=database_name;host=hostname;port=port
.Ve
.Sp
There is \fIno standard\fR for the text following the driver name. Each
driver is free to use whatever syntax it wants. The only requirement the
\&\s-1DBI\s0 makes is that all the information is supplied in a single string.
You must consult the documentation for the drivers you are using for a
description of the syntax they require. (Where a driver author needs
to define a syntax for the \f(CW$data_source\fR, it is recommended that
they follow the \s-1ODBC\s0 style, shown in the last example above.)
.Sp
If the environment variable \f(CW\*(C`DBI_AUTOPROXY\*(C'\fR is defined (and the driver in
\&\f(CW$data_source\fR is not "\f(CW\*(C`Proxy\*(C'\fR") then the connect request will
automatically be changed to:
.Sp
.Vb 1
\& dbi:Proxy:$ENV{DBI_AUTOPROXY};dsn=$data_source
.Ve
.Sp
and passed to the DBD::Proxy module. \f(CW\*(C`DBI_AUTOPROXY\*(C'\fR is typically set as
"\f(CW\*(C`hostname=...;port=...\*(C'\fR". See the DBD::Proxy documentation for more details.
.Sp
If \f(CW$username\fR or \f(CW$password\fR are undefined (rather than just empty),
then the \s-1DBI\s0 will substitute the values of the \f(CW\*(C`DBI_USER\*(C'\fR and \f(CW\*(C`DBI_PASS\*(C'\fR
environment variables, respectively. The \s-1DBI\s0 will warn if the
environment variables are not defined. However, the everyday use of
these environment
variables is not recommended for security reasons. The mechanism is
primarily intended to simplify testing.
.Sp
\&\f(CW\*(C`DBI\-\*(C'\fR>\f(CW\*(C`connect\*(C'\fR automatically installs the driver if it has not been
installed yet. Driver installation either returns a valid driver
handle, or it \fIdies\fR with an error message that includes the string
"\f(CW\*(C`install_driver\*(C'\fR" and the underlying problem. So \f(CW\*(C`DBI\-\*(C'\fR>\f(CW\*(C`connect\*(C'\fR
will die
on a driver installation failure and will only return \f(CW\*(C`undef\*(C'\fR on a
connect failure, in which case \f(CW$DBI::errstr\fR will hold the error message.
.Sp
The \f(CW$data_source\fR argument (with the "\f(CW\*(C`dbi:...:\*(C'\fR" prefix removed) and the
\&\f(CW$username\fR and \f(CW$password\fR arguments are then passed to the driver for
processing. The \s-1DBI\s0 does not define any interpretation for the
contents of these fields. The driver is free to interpret the
\&\f(CW$data_source\fR, \f(CW$username\fR, and \f(CW$password\fR fields in any way, and supply
whatever defaults are appropriate for the engine being accessed.
(Oracle, for example, uses the \s-1ORACLE_SID\s0 and \s-1TWO_TASK\s0 environment
variables if no \f(CW$data_source\fR is specified.)
.Sp
The \f(CW\*(C`AutoCommit\*(C'\fR and \f(CW\*(C`PrintError\*(C'\fR attributes for each connection default to
\&\*(L"on\*(R". (See \*(L"AutoCommit\*(R" and \*(L"PrintError\*(R" for more information.)
However, it is strongly recommended that you explicitly define \f(CW\*(C`AutoCommit\*(C'\fR
rather than rely on the default. Future versions of
the \s-1DBI\s0 may issue a warning if \f(CW\*(C`AutoCommit\*(C'\fR is not explicitly defined.
.Sp
The \f(CW\*(C`\e%attr\*(C'\fR parameter can be used to alter the default settings of
\&\f(CW\*(C`PrintError\*(C'\fR, \f(CW\*(C`RaiseError\*(C'\fR, \f(CW\*(C`AutoCommit\*(C'\fR, and other attributes. For example:
.Sp
.Vb 4
\& $dbh = DBI->connect($data_source, $user, $pass, {
\& PrintError => 0,
\& AutoCommit => 0
\& });
.Ve
.Sp
You can also define connection attribute values within the \f(CW$data_source\fR
parameter. For example:
.Sp
.Vb 1
\& dbi:DriverName(PrintError=>0,Taint=>1):...
.Ve
.Sp
Individual attributes values specified in this way take precedence over
any conflicting values specified via the \f(CW\*(C`\e%attr\*(C'\fR parameter to \f(CW\*(C`connect\*(C'\fR.
.Sp
The \f(CW\*(C`dbi_connect_method\*(C'\fR attribute can be used to specify which driver
method should be called to establish the connection. The only useful
values are 'connect', 'connect_cached', or some specialized case like
\&'Apache::DBI::connect' (which is automatically the default when running
within Apache).
.Sp
Where possible, each session (\f(CW$dbh\fR) is independent from the transactions
in other sessions. This is useful when you need to hold cursors open
across transactions\*(--for example, if you use one session for your long lifespan
cursors (typically read\-only) and another for your short update
transactions.
.Sp
For compatibility with old \s-1DBI\s0 scripts, the driver can be specified by
passing its name as the fourth argument to \f(CW\*(C`connect\*(C'\fR (instead of \f(CW\*(C`\e%attr\*(C'\fR):
.Sp
.Vb 1
\& $dbh = DBI->connect($data_source, $user, $pass, $driver);
.Ve
.Sp
In this \*(L"old\-style\*(R" form of \f(CW\*(C`connect\*(C'\fR, the \f(CW$data_source\fR should not start
with "\f(CW\*(C`dbi:driver_name:\*(C'\fR". (If it does, the embedded driver_name
will be ignored). Also note that in this older form of \f(CW\*(C`connect\*(C'\fR,
the \f(CW\*(C`$dbh\-\*(C'\fR>\f(CW\*(C`{AutoCommit}\*(C'\fR attribute is \fIundefined\fR, the
\&\f(CW\*(C`$dbh\-\*(C'\fR>\f(CW\*(C`{PrintError}\*(C'\fR attribute is off, and the old \f(CW\*(C`DBI_DBNAME\*(C'\fR
environment variable is
checked if \f(CW\*(C`DBI_DSN\*(C'\fR is not defined. Beware that this \*(L"old\-style\*(R"
\&\f(CW\*(C`connect\*(C'\fR will be withdrawn in a future version of \s-1DBI\s0.
.ie n .IP """connect_cached""\fR \fI\s-1NEW\s0" 4
.el .IP "\f(CWconnect_cached\fR \fI\s-1NEW\s0\fR" 4
.IX Item "connect_cached NEW"
.Vb 4
\& $dbh = DBI->connect_cached($data_source, $username, $password)
\& or die $DBI::errstr;
\& $dbh = DBI->connect_cached($data_source, $username, $password, \e%attr)
\& or die $DBI::errstr;
.Ve
.Sp
\&\f(CW\*(C`connect_cached\*(C'\fR is like \*(L"connect\*(R", except that the database handle
returned is also
stored in a hash associated with the given parameters. If another call
is made to \f(CW\*(C`connect_cached\*(C'\fR with the same parameter values, then the
corresponding cached \f(CW$dbh\fR will be returned if it is still valid.
The cached database handle is replaced with a new connection if it
has been disconnected or if the \f(CW\*(C`ping\*(C'\fR method fails.
.Sp
Note that the behavior of this method differs in several respects from the
behavior of presistent connections implemented by Apache::DBI.
.Sp
Caching can be useful in some applications, but it can also cause
problems and should be used with care. The exact behavior of this
method is liable to change, so if you intend to use it in any production
applications you should discuss your needs on the \fIdbi-users\fR mailing list.
.Sp
The cache can be accessed (and cleared) via the \*(L"CachedKids\*(R" attribute.
.ie n .IP """available_drivers""" 4
.el .IP "\f(CWavailable_drivers\fR" 4
.IX Item "available_drivers"
.Vb 2
\& @ary = DBI->available_drivers;
\& @ary = DBI->available_drivers($quiet);
.Ve
.Sp
Returns a list of all available drivers by searching for \f(CW\*(C`DBD::*\*(C'\fR modules
through the directories in \f(CW@INC\fR. By default, a warning is given if
some drivers are hidden by others of the same name in earlier
directories. Passing a true value for \f(CW$quiet\fR will inhibit the warning.
.ie n .IP """data_sources""" 4
.el .IP "\f(CWdata_sources\fR" 4
.IX Item "data_sources"
.Vb 2
\& @ary = DBI->data_sources($driver);
\& @ary = DBI->data_sources($driver, \e%attr);
.Ve
.Sp
Returns a list of all data sources (databases) available via the named
driver. If \f(CW$driver\fR is empty or \f(CW\*(C`undef\*(C'\fR, then the value of the
\&\f(CW\*(C`DBI_DRIVER\*(C'\fR environment variable is used.
.Sp
The driver will be loaded if it hasn't been already. Note that if the
driver loading fails then it \fIdies\fR with an error message that
includes the string "\f(CW\*(C`install_driver\*(C'\fR" and the underlying problem.
.Sp
Data sources are returned in a form suitable for passing to the
\&\*(L"connect\*(R" method (that is, they will include the "\f(CW\*(C`dbi:$driver:\*(C'\fR" prefix).
.Sp
Note that many drivers have no way of knowing what data sources might
be available for it. These drivers return an empty or incomplete list
or may require driver-specific attributes, such as a connected database
handle, to be supplied.
.ie n .IP """trace""" 4
.el .IP "\f(CWtrace\fR" 4
.IX Item "trace"
.Vb 2
\& DBI->trace($trace_level)
\& DBI->trace($trace_level, $trace_filename)
.Ve
.Sp
\&\s-1DBI\s0 trace information can be enabled for all handles using the \f(CW\*(C`trace\*(C'\fR
\&\s-1DBI\s0 class method. To enable trace information for a specific handle, use
the similar \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`trace\*(C'\fR method described elsewhere.
.Sp
Trace levels are as follows:
.Sp
.Vb 8
\& 0 - Trace disabled.
\& 1 - Trace DBI method calls returning with results or errors.
\& 2 - Trace method entry with parameters and returning with results.
\& 3 - As above, adding some high-level information from the driver
\& and some internal information from the DBI.
\& 4 - As above, adding more detailed information from the driver.
\& Also includes DBI mutex information when using threaded Perl.
\& 5 and above - As above but with more and more obscure information.
.Ve
.Sp
Trace level 1 is best for a simple overview of what's happening.
Trace level 2 is a good choice for general purpose tracing. Levels 3
and above (up to 9) are best reserved for investigating a
specific problem, when you need to see \*(L"inside\*(R" the driver and \s-1DBI\s0.
.Sp
The trace output is detailed and typically very useful. Much of the
trace output is formatted using the \*(L"neat\*(R" function, so strings
in the trace output may be edited and truncated.
.Sp
Initially trace output is written to \f(CW\*(C`STDERR\*(C'\fR. If \f(CW$trace_filename\fR is
specified and can be opened in append mode then all trace
output (including that from other handles) is redirected to that file.
A warning is generated is the file can't be opened.
Further calls to \f(CW\*(C`trace\*(C'\fR without a \f(CW$trace_filename\fR do not alter where
the trace output is sent. If \f(CW$trace_filename\fR is undefined, then
trace output is sent to \f(CW\*(C`STDERR\*(C'\fR and the previous trace file is closed.
The \f(CW\*(C`trace\*(C'\fR method returns the \fIprevious\fR tracelevel.
.Sp
See also the \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`trace\*(C'\fR and \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`trace_msg\*(C'\fR methods and the
\&\*(L"\s-1DEBUGGING\s0\*(R" section
for information about the \f(CW\*(C`DBI_TRACE\*(C'\fR environment variable.
.Sh "\s-1DBI\s0 Utility Functions"
.IX Subsection "DBI Utility Functions"
In addition to the methods listed in the previous section,
the \s-1DBI\s0 package also provides these utility functions:
.ie n .IP """neat""" 4
.el .IP "\f(CWneat\fR" 4
.IX Item "neat"
.Vb 1
\& $str = DBI::neat($value, $maxlen);
.Ve
.Sp
Return a string containing a neat (and tidy) representation of the
supplied value.
.Sp
Strings will be quoted, although internal quotes will \fInot\fR be escaped.
Values known to be numeric will be unquoted. Undefined (\s-1NULL\s0) values
will be shown as \f(CW\*(C`undef\*(C'\fR (without quotes). Unprintable characters will
be replaced by dot (.).
.Sp
For result strings longer than \f(CW$maxlen\fR the result string will be
truncated to \f(CW\*(C`$maxlen\-4\*(C'\fR and "\f(CW\*(C`...'\*(C'\fR" will be appended. If \f(CW$maxlen\fR is 0
or \f(CW\*(C`undef\*(C'\fR, it defaults to \f(CW$DBI::neat_maxlen\fR which, in turn, defaults to 400.
.Sp
This function is designed to format values for human consumption.
It is used internally by the \s-1DBI\s0 for \*(L"trace\*(R" output. It should
typically \fInot\fR be used for formatting values for database use.
(See also \*(L"quote\*(R".)
.ie n .IP """neat_list""" 4
.el .IP "\f(CWneat_list\fR" 4
.IX Item "neat_list"
.Vb 1
\& $str = DBI::neat_list(\e@listref, $maxlen, $field_sep);
.Ve
.Sp
Calls \f(CW\*(C`DBI::neat\*(C'\fR on each element of the list and returns a string
containing the results joined with \f(CW$field_sep\fR. \f(CW$field_sep\fR defaults
to \f(CW", "\fR.
.ie n .IP """looks_like_number""" 4
.el .IP "\f(CWlooks_like_number\fR" 4
.IX Item "looks_like_number"
.Vb 1
\& @bool = DBI::looks_like_number(@array);
.Ve
.Sp
Returns true for each element that looks like a number.
Returns false for each element that does not look like a number.
Returns \f(CW\*(C`undef\*(C'\fR for each element that is undefined or empty.
.Sh "\s-1DBI\s0 Dynamic Attributes"
.IX Subsection "DBI Dynamic Attributes"
Dynamic attributes are always associated with the \fIlast handle used\fR
(that handle is represented by \f(CW$h\fR in the descriptions below).
.PP
Where an attribute is equivalent to a method call, then refer to
the method call for all related documentation.
.PP
Warning: these attributes are provided as a convenience but they
do have limitations. Specifically, they have a short lifespan:
because they are associated with
the last handle used, they should only be used \fIimmediately\fR after
calling the method that \*(L"sets\*(R" them.
If in any doubt, use the corresponding method call.
.ie n .IP "$DBI::err" 4
.el .IP "\f(CW$DBI::err\fR" 4
.IX Item "$DBI::err"
Equivalent to \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`err\*(C'\fR.
.ie n .IP "$DBI::errstr" 4
.el .IP "\f(CW$DBI::errstr\fR" 4
.IX Item "$DBI::errstr"
Equivalent to \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`errstr\*(C'\fR.
.ie n .IP "$DBI::state" 4
.el .IP "\f(CW$DBI::state\fR" 4
.IX Item "$DBI::state"
Equivalent to \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`state\*(C'\fR.
.ie n .IP "$DBI::rows" 4
.el .IP "\f(CW$DBI::rows\fR" 4
.IX Item "$DBI::rows"
Equivalent to \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`rows\*(C'\fR. Please refer to the documentation
for the \*(L"rows\*(R" method.
.ie n .IP "$DBI::lasth" 4
.el .IP "\f(CW$DBI::lasth\fR" 4
.IX Item "$DBI::lasth"
Returns the \s-1DBI\s0 object handle used for the most recent \s-1DBI\s0 method call.
If the last \s-1DBI\s0 method call was a \s-1DESTROY\s0 then \f(CW$DBI::lasth\fR will return
the handle of the parent of the destroyed handle, if there is one.
.SH "METHODS COMMON TO ALL HANDLES"
.IX Header "METHODS COMMON TO ALL HANDLES"
The following methods can be used by all types of \s-1DBI\s0 handles.
.ie n .IP """err""" 4
.el .IP "\f(CWerr\fR" 4
.IX Item "err"
.Vb 1
\& $rv = $h->err;
.Ve
.Sp
Returns the \fInative\fR database engine error code from the last driver
method called. The code is typically an integer but you should not
assume that.
.Sp
The \s-1DBI\s0 resets \f(CW$h\fR\->err to undef before most \s-1DBI\s0 method calls, so the
value only has a short lifespan. Also, most drivers share the same
error variables across all their handles, so calling a method on
one handle will typically reset the error on all the other handles
that are children of that driver.
.Sp
If you need to test for individual errors \fIand\fR have your program be
portable to different database engines, then you'll need to determine
what the corresponding error codes are for all those engines and test for
all of them.
.ie n .IP """errstr""" 4
.el .IP "\f(CWerrstr\fR" 4
.IX Item "errstr"
.Vb 1
\& $str = $h->errstr;
.Ve
.Sp
Returns the native database engine error message from the last driver
method called. This has the same lifespan issues as the \*(L"err\*(R" method
described above.
.ie n .IP """state""" 4
.el .IP "\f(CWstate\fR" 4
.IX Item "state"
.Vb 1
\& $str = $h->state;
.Ve
.Sp
Returns an error code in the standard \s-1SQLSTATE\s0 five character format.
Note that the specific success code \f(CW00000\fR is translated to ''
(false). If the driver does not support \s-1SQLSTATE\s0 (and most don't),
then state will return \f(CW\*(C`S1000\*(C'\fR (General Error) for all errors.
.Sp
The driver is free to return any value via \f(CW\*(C`state\*(C'\fR, e.g., warning
codes, even if it has not declared an error by returning a true value
via the \*(L"err\*(R" method described above.
.ie n .IP """trace""" 4
.el .IP "\f(CWtrace\fR" 4
.IX Item "trace"
.Vb 2
\& $h->trace($trace_level);
\& $h->trace($trace_level, $trace_filename);
.Ve
.Sp
\&\s-1DBI\s0 trace information can be enabled for a specific handle (and any
future children of that handle) by setting the trace level using the
\&\f(CW\*(C`trace\*(C'\fR method.
.Sp
Trace level 1 is best for a simple overview of what's happening.
Trace level 2 is a good choice for general purpose tracing. Levels 3
and above (up to 9) are best reserved for investigating a
specific problem, when you need to see \*(L"inside\*(R" the driver and \s-1DBI\s0.
Set \f(CW$trace_level\fR to 0 to disable the trace.
.Sp
The trace output is detailed and typically very useful. Much of the
trace output is formatted using the \*(L"neat\*(R" function, so strings
in the trace output may be edited and truncated.
.Sp
Initially, trace output is written to \f(CW\*(C`STDERR\*(C'\fR. If \f(CW$trace_filename\fR is
specified, then the file is opened in append mode and \fIall\fR trace
output (including that from other handles) is redirected to that file.
Further calls to trace without a \f(CW$trace_filename\fR do not alter where
the trace output is sent. If \f(CW$trace_filename\fR is undefined, then
trace output is sent to \f(CW\*(C`STDERR\*(C'\fR and the previous trace file is closed.
.Sp
See also the \f(CW\*(C`DBI\-\*(C'\fR>\f(CW\*(C`trace\*(C'\fR method and \*(L"\s-1DEBUGGING\s0\*(R" for information
about the \f(CW\*(C`DBI_TRACE\*(C'\fR environment variable.
.ie n .IP """trace_msg""" 4
.el .IP "\f(CWtrace_msg\fR" 4
.IX Item "trace_msg"
.Vb 2
\& $h->trace_msg($message_text);
\& $h->trace_msg($message_text, $min_level);
.Ve
.Sp
Writes \f(CW$message_text\fR to the trace file if trace is enabled for \f(CW$h\fR or
for the \s-1DBI\s0 as a whole. Can also be called as \f(CW\*(C`DBI\-\*(C'\fR>\f(CW\*(C`trace_msg($msg)\*(C'\fR.
See \*(L"trace\*(R".
.Sp
If \f(CW$min_level\fR is defined, then the message is output only if the trace
level is equal to or greater than that level. \f(CW$min_level\fR defaults to 1.
.ie n .IP """func""" 4
.el .IP "\f(CWfunc\fR" 4
.IX Item "func"
.Vb 1
\& $h->func(@func_arguments, $func_name);
.Ve
.Sp
The \f(CW\*(C`func\*(C'\fR method can be used to call private non-standard and
non-portable methods implemented by the driver. Note that the function
name is given as the last argument.
.Sp
This method is not directly related to calling stored procedures.
Calling stored procedures is currently not defined by the \s-1DBI\s0.
Some drivers, such as DBD::Oracle, support it in non-portable ways.
See driver documentation for more details.
.SH "ATTRIBUTES COMMON TO ALL HANDLES"
.IX Header "ATTRIBUTES COMMON TO ALL HANDLES"
These attributes are common to all types of \s-1DBI\s0 handles.
.PP
Some attributes are inherited by child handles. That is, the value
of an inherited attribute in a newly created statement handle is the
same as the value in the parent database handle. Changes to attributes
in the new statement handle do not affect the parent database handle
and changes to the database handle do not affect existing statement
handles, only future ones.
.PP
Attempting to set or get the value of an unknown attribute is fatal,
except for private driver specific attributes (which all have names
starting with a lowercase letter).
.PP
Example:
.PP
.Vb 2
\& $h->{AttributeName} = ...; # set/write
\& ... = $h->{AttributeName}; # get/read
.Ve
.ie n .IP """Warn"" (boolean, inherited)" 4
.el .IP "\f(CWWarn\fR (boolean, inherited)" 4
.IX Item "Warn (boolean, inherited)"
Enables useful warnings for certain bad practices. Enabled by default. Some
emulation layers, especially those for Perl 4 interfaces, disable warnings.
Since warnings are generated using the Perl \f(CW\*(C`warn\*(C'\fR function, they can be
intercepted using the Perl \f(CW$SIG{_\|_WARN_\|_}\fR hook.
.ie n .IP """Active"" (boolean, read\-only)" 4
.el .IP "\f(CWActive\fR (boolean, read\-only)" 4
.IX Item "Active (boolean, read-only)"
True if the handle object is \*(L"active\*(R". This is rarely used in
applications. The exact meaning of active is somewhat vague at the
moment. For a database handle it typically means that the handle is
connected to a database (\f(CW\*(C`$dbh\-\*(C'\fR>\f(CW\*(C`disconnect\*(C'\fR sets \f(CW\*(C`Active\*(C'\fR off). For
a statement handle it typically means that the handle is a \f(CW\*(C`SELECT\*(C'\fR
that may have more data to fetch. (Fetching all the data or calling \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`finish\*(C'\fR
sets \f(CW\*(C`Active\*(C'\fR off.)
.ie n .IP """Kids"" (integer, read\-only)" 4
.el .IP "\f(CWKids\fR (integer, read\-only)" 4
.IX Item "Kids (integer, read-only)"
For a driver handle, \f(CW\*(C`Kids\*(C'\fR is the number of currently existing database
handles that were created from that driver handle. For a database
handle, \f(CW\*(C`Kids\*(C'\fR is the number of currently existing statement handles that
were created from that database handle.
.ie n .IP """ActiveKids"" (integer, read\-only)" 4
.el .IP "\f(CWActiveKids\fR (integer, read\-only)" 4
.IX Item "ActiveKids (integer, read-only)"
Like \f(CW\*(C`Kids\*(C'\fR, but only counting those that are \f(CW\*(C`Active\*(C'\fR (as above).
.ie n .IP """CachedKids"" (hash ref)" 4
.el .IP "\f(CWCachedKids\fR (hash ref)" 4
.IX Item "CachedKids (hash ref)"
For a database handle, returns a reference to the cache (hash) of
statement handles created by the \*(L"prepare_cached\*(R" method. For a
driver handle, returns a reference to the cache (hash) of
database handles created by the \*(L"connect_cached\*(R" method.
.ie n .IP """CompatMode"" (boolean, inherited)" 4
.el .IP "\f(CWCompatMode\fR (boolean, inherited)" 4
.IX Item "CompatMode (boolean, inherited)"
Used by emulation layers (such as Oraperl) to enable compatible behavior
in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally
set by application code.
.ie n .IP """InactiveDestroy"" (boolean)" 4
.el .IP "\f(CWInactiveDestroy\fR (boolean)" 4
.IX Item "InactiveDestroy (boolean)"
This attribute can be used to disable the \fIdatabase engine\fR related
effect of DESTROYing a handle (which would normally close a prepared
statement or disconnect from the database etc).
.Sp
For a database handle, this attribute does not disable an \fIexplicit\fR
call to the disconnect method, only the implicit call from \s-1DESTROY\s0.
.Sp
This attribute is specifically designed for use in Unix applications
that \*(L"fork\*(R" child processes. Either the parent or the child process,
but not both, should set \f(CW\*(C`InactiveDestroy\*(C'\fR on all their shared handles.
Note that some databases, including Oracle, don't support passing a
database connection across a fork.
.ie n .IP """PrintError"" (boolean, inherited)" 4
.el .IP "\f(CWPrintError\fR (boolean, inherited)" 4
.IX Item "PrintError (boolean, inherited)"
This attribute can be used to force errors to generate warnings (using
\&\f(CW\*(C`warn\*(C'\fR) in addition to returning error codes in the normal way. When set
\&\*(L"on\*(R", any method which results in an error occuring will cause the \s-1DBI\s0 to
effectively do a \f(CW\*(C`warn("$class $method failed: $DBI::errstr")\*(C'\fR where \f(CW$class\fR
is the driver class and \f(CW$method\fR is the name of the method which failed. E.g.,
.Sp
.Vb 1
\& DBD::Oracle::db prepare failed: ... error text here ...
.Ve
.Sp
By default, \f(CW\*(C`DBI\-\*(C'\fR>\f(CW\*(C`connect\*(C'\fR sets \f(CW\*(C`PrintError\*(C'\fR \*(L"on\*(R".
.Sp
If desired, the warnings can be caught and processed using a \f(CW$SIG{_\|_WARN_\|_}\fR
handler or modules like CGI::Carp and CGI::ErrorWrap.
.ie n .IP """RaiseError"" (boolean, inherited)" 4
.el .IP "\f(CWRaiseError\fR (boolean, inherited)" 4
.IX Item "RaiseError (boolean, inherited)"
This attribute can be used to force errors to raise exceptions rather
than simply return error codes in the normal way. It is \*(L"off\*(R" by default.
When set \*(L"on\*(R", any method which results in an error will cause
the \s-1DBI\s0 to effectively do a \f(CW\*(C`die("$class $method failed: $DBI::errstr")\*(C'\fR,
where \f(CW$class\fR is the driver class and \f(CW$method\fR is the name of the method
that failed. E.g.,
.Sp
.Vb 1
\& DBD::Oracle::db prepare failed: ... error text here ...
.Ve
.Sp
If you turn \f(CW\*(C`RaiseError\*(C'\fR on then you'd normally turn \f(CW\*(C`PrintError\*(C'\fR off.
If \f(CW\*(C`PrintError\*(C'\fR is also on, then the \f(CW\*(C`PrintError\*(C'\fR is done first (naturally).
.Sp
Typically \f(CW\*(C`RaiseError\*(C'\fR is used in conjunction with \f(CW\*(C`eval { ... }\*(C'\fR
to catch the exception that's been thrown and followed by an
\&\f(CW\*(C`if ($@) { ... }\*(C'\fR block to handle the caught exception. In that eval
block the \f(CW$DBI::lasth\fR variable can be useful for diagnosis and reporting.
For example, \f(CW$DBI::lasth\fR\->{Type} and \f(CW$DBI::lasth\fR\->{Statement}.
.Sp
If you want to temporarily turn \f(CW\*(C`RaiseError\*(C'\fR off (inside a library function
that is likely to fail, for example), the recommended way is like this:
.Sp
.Vb 4
\& {
\& local $h->{RaiseError}; # localize and turn off for this block
\& ...
\& }
.Ve
.Sp
The original value will automatically and reliably be restored by Perl,
regardless of how the block is exited.
The same logic applies to other attributes, including \f(CW\*(C`PrintError\*(C'\fR.
.Sp
Sadly, this doesn't work for Perl versions up to and including 5.004_04.
Even more sadly, for Perl 5.5 and 5.6.0 it does work but leaks memory!
For backwards compatibility, you could just use \f(CW\*(C`eval { ... }\*(C'\fR instead.
.ie n .IP """ShowErrorStatement""\fR (boolean, inherited) \fI\s-1NEW\s0" 4
.el .IP "\f(CWShowErrorStatement\fR (boolean, inherited) \fI\s-1NEW\s0\fR" 4
.IX Item "ShowErrorStatement (boolean, inherited) NEW"
This attribute can be used to cause the relevant Statement text to be
appended to the error messages generated by the \f(CW\*(C`RaiseError\*(C'\fR and
\&\f(CW\*(C`PrintError\*(C'\fR attributes. Only applies to errors on statement handles
plus the \fIprepare()\fR and \fIdo()\fR database handle methods.
(The exact format of the appended text is subject to change.)
.ie n .IP """ChopBlanks"" (boolean, inherited)" 4
.el .IP "\f(CWChopBlanks\fR (boolean, inherited)" 4
.IX Item "ChopBlanks (boolean, inherited)"
This attribute can be used to control the trimming of trailing space
characters from fixed width character (\s-1CHAR\s0) fields. No other field
types are affected, even where field values have trailing spaces.
.Sp
The default is false (although it is possible that the default may change).
Applications that need specific behavior should set the attribute as
needed. Emulation interfaces should set the attribute to match the
behavior of the interface they are emulating.
.Sp
Drivers are not required to support this attribute, but any driver which
does not support it must arrange to return \f(CW\*(C`undef\*(C'\fR as the attribute value.
.ie n .IP """LongReadLen"" (unsigned integer, inherited)" 4
.el .IP "\f(CWLongReadLen\fR (unsigned integer, inherited)" 4
.IX Item "LongReadLen (unsigned integer, inherited)"
This attribute may be used to control the maximum length of long fields
(\*(L"blob\*(R", \*(L"memo\*(R", etc.) which the driver will read from the
database automatically when it fetches each row of data. The
\&\f(CW\*(C`LongReadLen\*(C'\fR attribute only relates to fetching and reading long values; it
is not involved in inserting or updating them.
.Sp
A value of 0 means not to automatically fetch any long data. (\f(CW\*(C`fetch\*(C'\fR
should return \f(CW\*(C`undef\*(C'\fR for long fields when \f(CW\*(C`LongReadLen\*(C'\fR is 0.)
.Sp
The default is typically 0 (zero) bytes but may vary between drivers.
Applications fetching long fields should set this value to slightly
larger than the longest long field value to be fetched.
.Sp
Some databases return some long types encoded as pairs of hex digits.
For these types, \f(CW\*(C`LongReadLen\*(C'\fR relates to the underlying data length and not the
doubled-up length of the encoded string.
.Sp
Changing the value of \f(CW\*(C`LongReadLen\*(C'\fR for a statement handle after it
has been \f(CW\*(C`prepare\*(C'\fR'd will typically have no effect, so it's common to
set \f(CW\*(C`LongReadLen\*(C'\fR on the \f(CW$dbh\fR before calling \f(CW\*(C`prepare\*(C'\fR.
.Sp
Note that the value used here has a direct effect on the memory used
by the application, so don't be too generous.
.Sp
See \*(L"LongTruncOk\*(R" for more information on truncation behavior.
.ie n .IP """LongTruncOk"" (boolean, inherited)" 4
.el .IP "\f(CWLongTruncOk\fR (boolean, inherited)" 4
.IX Item "LongTruncOk (boolean, inherited)"
This attribute may be used to control the effect of fetching a long
field value which has been truncated (typically because it's longer
than the value of the \f(CW\*(C`LongReadLen\*(C'\fR attribute).
.Sp
By default, \f(CW\*(C`LongTruncOk\*(C'\fR is false and so fetching a long value that
needs to be truncated will cause the fetch to fail.
(Applications should always be sure to
check for errors after a fetch loop in case an error, such as a divide
by zero or long field truncation, caused the fetch to terminate
prematurely.)
.Sp
If a fetch fails due to a long field truncation when \f(CW\*(C`LongTruncOk\*(C'\fR is
false, many drivers will allow you to continue fetching further rows.
.Sp
See also \*(L"LongReadLen\*(R".
.ie n .IP """Taint"" (boolean, inherited)" 4
.el .IP "\f(CWTaint\fR (boolean, inherited)" 4
.IX Item "Taint (boolean, inherited)"
If this attribute is set to a true value \fIand\fR Perl is running in
taint mode (e.g., started with the \f(CW\*(C`\-T\*(C'\fR option), then all data
fetched from the database is tainted, and the arguments to most \s-1DBI\s0
method calls are checked for being tainted. \fIThis may change.\fR
.Sp
The attribute defaults to off, even if Perl is in taint mode.
See perlsec for more about taint mode. If Perl is not
running in taint mode, this attribute has no effect.
.Sp
When fetching data that you trust you can turn off the Taint attribute,
for that statement handle, for the duration of the fetch loop.
.Sp
Currently only fetched data is tainted. It is possible that the results
of other \s-1DBI\s0 method calls, and the value of fetched attributes, may
also be tainted in future versions. That change may well break your
applications unless you take great care now. If you use \s-1DBI\s0 Taint mode,
please report your experience and any suggestions for changes.
.ie n .IP """private_*""" 4
.el .IP "\f(CWprivate_*\fR" 4
.IX Item "private_*"
The \s-1DBI\s0 provides a way to store extra information in a \s-1DBI\s0 handle as
\&\*(L"private\*(R" attributes. The \s-1DBI\s0 will allow you to store and retreive any
attribute which has a name starting with "\f(CW\*(C`private_\*(C'\fR". It is strongly
recommended that you use just \fIone\fR private attribute (e.g., use a
hash ref) and give it a long and unambiguous name that includes the
module or application name that the attribute relates to (e.g.,
"\f(CW\*(C`private_YourFullModuleName_thingy\*(C'\fR").
.SH "DBI DATABASE HANDLE OBJECTS"
.IX Header "DBI DATABASE HANDLE OBJECTS"
This section covers the methods and attributes associated with
database handles.
.Sh "Database Handle Methods"
.IX Subsection "Database Handle Methods"
The following methods are specified for \s-1DBI\s0 database handles:
.ie n .IP """do""" 4
.el .IP "\f(CWdo\fR" 4
.IX Item "do"
.Vb 3
\& $rc = $dbh->do($statement) or die $dbh->errstr;
\& $rc = $dbh->do($statement, \e%attr) or die $dbh->errstr;
\& $rv = $dbh->do($statement, \e%attr, @bind_values) or ...
.Ve
.Sp
Prepare and execute a single statement. Returns the number of rows
affected or \f(CW\*(C`undef\*(C'\fR on error. A return value of \f(CW\*(C`\-1\*(C'\fR means the
number of rows is not known or is not available.
.Sp
This method is typically most useful for \fInon\fR\-\f(CW\*(C`SELECT\*(C'\fR statements that
either cannot be prepared in advance (due to a limitation of the
driver) or do not need to be executed repeatedly. It should not
be used for \f(CW\*(C`SELECT\*(C'\fR statements because it does not return a statement
handle (so you can't fetch any data).
.Sp
The default \f(CW\*(C`do\*(C'\fR method is logically similar to:
.Sp
.Vb 7
\& sub do {
\& my($dbh, $statement, $attr, @bind_values) = @_;
\& my $sth = $dbh->prepare($statement, $attr) or return undef;
\& $sth->execute(@bind_values) or return undef;
\& my $rows = $sth->rows;
\& ($rows == 0) ? "0E0" : $rows; # always return true if no error
\& }
.Ve
.Sp
For example:
.Sp
.Vb 4
\& my $rows_deleted = $dbh->do(q{
\& DELETE FROM table
\& WHERE status = ?
\& }, undef, 'DONE') or die $dbh->errstr;
.Ve
.Sp
Using placeholders and \f(CW@bind_values\fR with the \f(CW\*(C`do\*(C'\fR method can be
useful because it avoids the need to correctly quote any variables
in the \f(CW$statement\fR. But if you'll be executing the statement many
times then it's more efficient to \f(CW\*(C`prepare\*(C'\fR it once and call
\&\f(CW\*(C`execute\*(C'\fR many times instead.
.Sp
The \f(CW\*(C`q{...}\*(C'\fR style quoting used in this example avoids clashing with
quotes that may be used in the \s-1SQL\s0 statement. Use the double-quote-like
\&\f(CW\*(C`qq{...}\*(C'\fR operator if you want to interpolate variables into the string.
See \*(L"Quote and Quote-like Operators\*(R" in perlop for more details.
.ie n .IP """selectrow_array""" 4
.el .IP "\f(CWselectrow_array\fR" 4
.IX Item "selectrow_array"
.Vb 3
\& @row_ary = $dbh->selectrow_array($statement);
\& @row_ary = $dbh->selectrow_array($statement, \e%attr);
\& @row_ary = $dbh->selectrow_array($statement, \e%attr, @bind_values);
.Ve
.Sp
This utility method combines \*(L"prepare\*(R", \*(L"execute\*(R" and
\&\*(L"fetchrow_array\*(R" into a single call. If called in a list context, it
returns the first row of data from the statement. If called in a scalar
context, it returns the first field of the first row. The \f(CW$statement\fR
parameter can be a previously prepared statement handle, in which case
the \f(CW\*(C`prepare\*(C'\fR is skipped.
.Sp
If any method fails, and \*(L"RaiseError\*(R" is not set, \f(CW\*(C`selectrow_array\*(C'\fR
will return an empty list.
.Sp
In a scalar context, \f(CW\*(C`selectrow_array\*(C'\fR returns the value of the first
field. An \f(CW\*(C`undef\*(C'\fR is returned if there are no matching rows or an error
occurred. Since that \f(CW\*(C`undef\*(C'\fR can't be distinguished from an \f(CW\*(C`undef\*(C'\fR returned
because the first field value was \s-1NULL\s0, calling \f(CW\*(C`selectrow_array\*(C'\fR in
a scalar context should be used with caution.
.ie n .IP """selectall_arrayref""" 4
.el .IP "\f(CWselectall_arrayref\fR" 4
.IX Item "selectall_arrayref"
.Vb 3
\& $ary_ref = $dbh->selectall_arrayref($statement);
\& $ary_ref = $dbh->selectall_arrayref($statement, \e%attr);
\& $ary_ref = $dbh->selectall_arrayref($statement, \e%attr, @bind_values);
.Ve
.Sp
This utility method combines \*(L"prepare\*(R", \*(L"execute\*(R" and
\&\*(L"fetchall_arrayref\*(R" into a single call. It returns a reference to an
array containing a reference to an array for each row of data fetched.
.Sp
The \f(CW$statement\fR parameter can be a previously prepared statement handle,
in which case the \f(CW\*(C`prepare\*(C'\fR is skipped. This is recommended if the
statement is going to be executed many times.
.Sp
If \*(L"RaiseError\*(R" is not set and any method except \f(CW\*(C`fetchall_arrayref\*(C'\fR
fails then \f(CW\*(C`selectall_arrayref\*(C'\fR will return \f(CW\*(C`undef\*(C'\fR; if
\&\f(CW\*(C`fetchall_arrayref\*(C'\fR fails then it will return with whatever data it
has been fetched thus far. \f(CW$DBI::err\fR should be checked to catch that.
.ie n .IP """selectall_hashref""" 4
.el .IP "\f(CWselectall_hashref\fR" 4
.IX Item "selectall_hashref"
.Vb 3
\& $ary_ref = $dbh->selectall_hashref($statement);
\& $ary_ref = $dbh->selectall_hashref($statement, \e%attr);
\& $ary_ref = $dbh->selectall_hashref($statement, \e%attr, @bind_values);
.Ve
.Sp
This utility method combines \*(L"prepare\*(R", \*(L"execute\*(R" and
\&\*(L"fetchrow_hashref\*(R" into a single call. It returns a reference to an
array containing, for each row of data fetched, a reference to a hash
containing field name and value pairs for that row.
.Sp
The \f(CW$statement\fR parameter can be a previously prepared statement handle,
in which case the \f(CW\*(C`prepare\*(C'\fR is skipped. This is recommended if the
statement is going to be executed many times.
.Sp
If any method except \f(CW\*(C`fetchrow_hashref\*(C'\fR fails, and \*(L"RaiseError\*(R" is not set,
\&\f(CW\*(C`selectall_hashref\*(C'\fR will return \f(CW\*(C`undef\*(C'\fR. If \f(CW\*(C`fetchrow_hashref\*(C'\fR fails and
\&\*(L"RaiseError\*(R" is not set, then it will return with whatever data it
has fetched thus far. \f(CW$DBI::err\fR should be checked to catch that.
.ie n .IP """selectcol_arrayref""" 4
.el .IP "\f(CWselectcol_arrayref\fR" 4
.IX Item "selectcol_arrayref"
.Vb 3
\& $ary_ref = $dbh->selectcol_arrayref($statement);
\& $ary_ref = $dbh->selectcol_arrayref($statement, \e%attr);
\& $ary_ref = $dbh->selectcol_arrayref($statement, \e%attr, @bind_values);
.Ve
.Sp
This utility method combines \*(L"prepare\*(R", \*(L"execute\*(R", and fetching one
column from all the rows, into a single call. It returns a reference to
an array containing the values of the first column from each row.
.Sp
The \f(CW$statement\fR parameter can be a previously prepared statement handle,
in which case the \f(CW\*(C`prepare\*(C'\fR is skipped. This is recommended if the
statement is going to be executed many times.
.Sp
If any method except \f(CW\*(C`fetch\*(C'\fR fails, and \*(L"RaiseError\*(R" is not set,
\&\f(CW\*(C`selectcol_arrayref\*(C'\fR will return \f(CW\*(C`undef\*(C'\fR. If \f(CW\*(C`fetch\*(C'\fR fails and
\&\*(L"RaiseError\*(R" is not set, then it will return with whatever data it
has fetched thus far. \f(CW$DBI::err\fR should be checked to catch that.
.ie n .IP """prepare""" 4
.el .IP "\f(CWprepare\fR" 4
.IX Item "prepare"
.Vb 2
\& $sth = $dbh->prepare($statement) or die $dbh->errstr;
\& $sth = $dbh->prepare($statement, \e%attr) or die $dbh->errstr;
.Ve
.Sp
Prepares a single statement for later execution by the database
engine and returns a reference to a statement handle object.
.Sp
The returned statement handle can be used to get attributes of the
statement and invoke the \*(L"execute\*(R" method. See \*(L"Statement Handle Methods\*(R".
.Sp
Drivers for engines without the concept of preparing a
statement will typically just store the statement in the returned
handle and process it when \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`execute\*(C'\fR is called. Such drivers are
unlikely to give much useful information about the
statement, such as \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`{NUM_OF_FIELDS}\*(C'\fR, until after \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`execute\*(C'\fR
has been called. Portable applications should take this into account.
.Sp
In general, \s-1DBI\s0 drivers do not parse the contents of the statement
(other than simply counting any \*(L"Placeholders\*(R"). The statement is
passed directly to the database engine, sometimes known as pass-thru
mode. This has advantages and disadvantages. On the plus side, you can
access all the functionality of the engine being used. On the downside,
you're limited if you're using a simple engine, and you need to take extra care if
writing applications intended to be portable between engines.
.Sp
Portable applications should not assume that a new statement can be
prepared and/or executed while still fetching results from a previous
statement.
.Sp
Some command-line \s-1SQL\s0 tools use statement terminators, like a semicolon,
to indicate the end of a statement. Such terminators should not normally
be used with the \s-1DBI\s0.
.ie n .IP """prepare_cached""" 4
.el .IP "\f(CWprepare_cached\fR" 4
.IX Item "prepare_cached"
.Vb 3
\& $sth = $dbh->prepare_cached($statement)
\& $sth = $dbh->prepare_cached($statement, \e%attr)
\& $sth = $dbh->prepare_cached($statement, \e%attr, $allow_active)
.Ve
.Sp
Like \*(L"prepare\*(R" except that the statement handle returned will be
stored in a hash associated with the \f(CW$dbh\fR. If another call is made to
\&\f(CW\*(C`prepare_cached\*(C'\fR with the same \f(CW$statement\fR and \f(CW%attr\fR values, then the
corresponding cached \f(CW$sth\fR will be returned without contacting the
database server.
.Sp
This caching can be useful in some applications, but it can also cause
problems and should be used with care. If the cached \f(CW$sth\fR being
returned is active (i.e., is a \f(CW\*(C`SELECT\*(C'\fR that may still have data to be
fetched) then a warning will be generated and \f(CW\*(C`finish\*(C'\fR will be called
for you. The warning can be suppressed by setting \f(CW$allow_active\fR to
true. The cache can be accessed (and cleared) via the \*(L"CachedKids\*(R"
attribute.
.Sp
Here's an example of one possible use of \f(CW\*(C`prepare_cached\*(C'\fR:
.Sp
.Vb 8
\& while ( ($field, $value) = each %search_fields ) {
\& push @sql, "$field = ?";
\& push @values, $value;
\& }
\& $qualifier = "";
\& $qualifier = "where ".join(" and ", @sql) if @sql;
\& $sth = $dbh->prepare_cached("SELECT * FROM table $qualifier");
\& $sth->execute(@values);
.Ve
.ie n .IP """commit""" 4
.el .IP "\f(CWcommit\fR" 4
.IX Item "commit"
.Vb 1
\& $rc = $dbh->commit or die $dbh->errstr;
.Ve
.Sp
Commit (make permanent) the most recent series of database changes
if the database supports transactions and AutoCommit is off.
.Sp
If \f(CW\*(C`AutoCommit\*(C'\fR is on, then calling
\&\f(CW\*(C`commit\*(C'\fR will issue a \*(L"commit ineffective with AutoCommit\*(R" warning.
.Sp
See also \*(L"Transactions\*(R" in the \*(L"\s-1FURTHER\s0 \s-1INFORMATION\s0\*(R" section below.
.ie n .IP """rollback""" 4
.el .IP "\f(CWrollback\fR" 4
.IX Item "rollback"
.Vb 1
\& $rc = $dbh->rollback or die $dbh->errstr;
.Ve
.Sp
Rollback (undo) the most recent series of uncommitted database
changes if the database supports transactions and AutoCommit is off.
.Sp
If \f(CW\*(C`AutoCommit\*(C'\fR is on, then calling
\&\f(CW\*(C`rollback\*(C'\fR will issue a \*(L"rollback ineffective with AutoCommit\*(R" warning.
.Sp
See also \*(L"Transactions\*(R" in the \*(L"\s-1FURTHER\s0 \s-1INFORMATION\s0\*(R" section below.
.ie n .IP """disconnect""" 4
.el .IP "\f(CWdisconnect\fR" 4
.IX Item "disconnect"
.Vb 1
\& $rc = $dbh->disconnect or warn $dbh->errstr;
.Ve
.Sp
Disconnects the database from the database handle. \f(CW\*(C`disconnect\*(C'\fR is typically only used
before exiting the program. The handle is of little use after disconnecting.
.Sp
The transaction behavior of the \f(CW\*(C`disconnect\*(C'\fR method is, sadly,
undefined. Some database systems (such as Oracle and Ingres) will
automatically commit any outstanding changes, but others (such as
Informix) will rollback any outstanding changes. Applications not
using \f(CW\*(C`AutoCommit\*(C'\fR should explicitly call \f(CW\*(C`commit\*(C'\fR or \f(CW\*(C`rollback\*(C'\fR before
calling \f(CW\*(C`disconnect\*(C'\fR.
.Sp
The database is automatically disconnected by the \f(CW\*(C`DESTROY\*(C'\fR method if
still connected when there are no longer any references to the handle.
The \f(CW\*(C`DESTROY\*(C'\fR method for each driver should implicitly call \f(CW\*(C`rollback\*(C'\fR to
undo any uncommitted changes. This is vital behavior to ensure that
incomplete transactions don't get committed simply because Perl calls
\&\f(CW\*(C`DESTROY\*(C'\fR on every object before exiting. Also, do not rely on the order
of object destruction during \*(L"global destruction\*(R", as it is undefined.
.Sp
Generally, if you want your changes to be commited or rolled back when
you disconnect, then you should explicitly call \*(L"commit\*(R" or \*(L"rollback\*(R"
before disconnecting.
.Sp
If you disconnect from a database while you still have active statement
handles, you will get a warning. The statement handles should either be
cleared (destroyed) before disconnecting, or the \f(CW\*(C`finish\*(C'\fR method
should be called on
each one.
.ie n .IP """ping""" 4
.el .IP "\f(CWping\fR" 4
.IX Item "ping"
.Vb 1
\& $rc = $dbh->ping;
.Ve
.Sp
Attempts to determine, in a reasonably efficient way, if the database
server is still running and the connection to it is still working.
Individual drivers should implement this function in the most suitable
manner for their database engine.
.Sp
The current \fIdefault\fR implementation always returns true without
actually doing anything. Actually, it returns "\f(CW\*(C`0 but true\*(C'\fR" which is
true but zero. That way you can tell if the return value is genuine or
just the default. Drivers should override this method with one that
does the right thing for their type of database.
.Sp
Few applications would have direct use for this method. See the specialized
Apache::DBI module for one example usage.
.ie n .IP """table_info""\fR \fI\s-1NEW\s0" 4
.el .IP "\f(CWtable_info\fR \fI\s-1NEW\s0\fR" 4
.IX Item "table_info NEW"
\&\fBWarning:\fR This method is experimental and may change.
.Sp
.Vb 2
\& $sth = $dbh->table_info;
\& $sth = $dbh->table_info( \e%attr );
.Ve
.Sp
Returns an active statement handle that can be used to fetch
information about tables and views that exist in the database.
.Sp
The following attributes (all or separate) may be used as selection criteria:
.Sp
.Vb 6
\& %attr = (
\& TABLE_CAT => $CatVal # String value of the catalog name
\& , TABLE_SCHEM => $SchVal # String value of the schema name
\& , TABLE_NAME => $TblVal # String value of the table name
\& , TABLE_TYPE => $TypVal # String value of the table type(s)
\& );
.Ve
.Sp
Note: The support for the selection criteria is driver specific. If the
driver doesn't support one or more then them then you'll get back more
than you asked for and can do the filtering yourself.
.Sp
The arguments \s-1TABLE_CAT\s0, \s-1TABLE_SCHEM\s0 and \s-1TABLE_NAME\s0 may accept search
patterns according to the database/driver, for example:
.Sp
.Vb 1
\& $sth = $dbh->table_info( { TABLE_NAME => '%TAB%'} );
.Ve
.Sp
The value of \s-1TABLE_TYPE\s0 is a comma-separated list of one or more types
of tables to be returned in the result set. Each value may optionally be
quoted, e.g.:
.Sp
.Vb 2
\& $sth = $dbh->table_info( { TABLE_TYPE => "TABLE" } );
\& $sth = $dbh->table_info( { TABLE_TYPE => "'TABLE', 'VIEW'" } );
.Ve
.Sp
In addition the following special cases may also be supported by some drivers:
.RS 4
.IP "\(bu If the value of \s-1TABLE_CAT\s0 is '%' and \s-1TABLE_SCHEM\s0 and \s-1TABLE_NAME\s0 name are empty strings, the result set contains a list of catalog names. For example:" 4
.IX Item "If the value of TABLE_CAT is '%' and TABLE_SCHEM and TABLE_NAME name are empty strings, the result set contains a list of catalog names. For example:"
.Vb 1
\& $sth = $dbh->table_info({ TABLE_CAT=>'%', TABLE_SCHEM=>'', TABLE_NAME=>'' });
.Ve
.IP "\(bu If the value of \s-1TABLE_SCHEM\s0 is '%' and \s-1TABLE_CAT\s0 and \s-1TABLE_NAME\s0 are empty strings, the result set contains a list of schema names." 4
.IX Item "If the value of TABLE_SCHEM is '%' and TABLE_CAT and TABLE_NAME are empty strings, the result set contains a list of schema names."
.PD 0
.IP "\(bu If the value of \s-1TABLE_TYPE\s0 is '%' and \s-1TABLE_CAT\s0, \s-1TABLE_SCHEM\s0, and \s-1TABLE_NAME\s0 are all empty strings, the result set contains a list of table types." 4
.IX Item "If the value of TABLE_TYPE is '%' and TABLE_CAT, TABLE_SCHEM, and TABLE_NAME are all empty strings, the result set contains a list of table types."
.RE
.RS 4
.PD
.Sp
The statement handle returned has at least the following fields in the
order show below. Other fields, after these, may also be present.
.Sp
\&\fB\s-1TABLE_CAT\s0\fR: Table catalog identifier. This field is \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) if not
applicable to the data source, which is usually the case. This field
is empty if not applicable to the table.
.Sp
\&\fB\s-1TABLE_SCHEM\s0\fR: The name of the schema containing the \s-1TABLE_NAME\s0 value.
This field is \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) if not applicable to data source, and
empty if not applicable to the table.
.Sp
\&\fB\s-1TABLE_NAME\s0\fR: Name of the table (or view, synonym, etc).
.Sp
\&\fB\s-1TABLE_TYPE\s0\fR: One of the following: \*(L"\s-1TABLE\s0\*(R", \*(L"\s-1VIEW\s0\*(R", \*(L"\s-1SYSTEM\s0 \s-1TABLE\s0\*(R",
\&\*(L"\s-1GLOBAL\s0 \s-1TEMPORARY\s0\*(R", \*(L"\s-1LOCAL\s0 \s-1TEMPORARY\s0\*(R", \*(L"\s-1ALIAS\s0\*(R", \*(L"\s-1SYNONYM\s0\*(R" or a type
identifier that is specific to the data
source.
.Sp
\&\fB\s-1REMARKS\s0\fR: A description of the table. May be \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR).
.Sp
Note that \f(CW\*(C`table_info\*(C'\fR might not return records for all tables.
Applications can use any valid table regardless of whether it's
returned by \f(CW\*(C`table_info\*(C'\fR. See also \*(L"tables\*(R".
.Sp
For more detailed information about the fields and their meanings,
you can refer to:
.Sp
.Vb 1
\& http://msdn.microsoft.com/library/psdk/dasdk/odch6wqb.htm
.Ve
.Sp
If that \s-1URL\s0 ceases to work then use the \s-1MSDN\s0 search facility at:
.Sp
.Vb 1
\& http://search.microsoft.com/us/dev/
.Ve
.Sp
and search for \f(CW\*(C`SQLTables returns\*(C'\fR using the exact phrase option.
The link you want will probably just be called \f(CW\*(C`SQLTables\*(C'\fR and will
be part of the Data Access \s-1SDK\s0.
.Sp
See also page 306 of the (very large) \s-1SQL/CLI\s0 specification:
.Sp
.Vb 1
\& http://www.jtc1sc32.org/sc32/jtc1sc32.nsf/Attachments/DF86E81BE70151D58525699800643F56/$FILE/32N0595T.PDF
.Ve
.RE
.ie n .IP """tables""\fR \fI\s-1NEW\s0" 4
.el .IP "\f(CWtables\fR \fI\s-1NEW\s0\fR" 4
.IX Item "tables NEW"
\&\fBWarning:\fR This method is experimental and may change.
.Sp
.Vb 2
\& @names = $dbh->tables;
\& @names = $dbh->tables( \e%attr );
.Ve
.Sp
Returns a list of table and view names, possibly including a schema prefix.
This list should include all
tables that can be used in a \f(CW\*(C`SELECT\*(C'\fR statement without further
qualification.
.Sp
Note that \f(CW\*(C`table_info\*(C'\fR might not return records for all tables.
Applications can use any valid table regardless of whether it's
returned by tables. See also \*(L"table_info\*(R".
.ie n .IP """type_info_all""\fR \fI\s-1NEW\s0" 4
.el .IP "\f(CWtype_info_all\fR \fI\s-1NEW\s0\fR" 4
.IX Item "type_info_all NEW"
\&\fBWarning:\fR This method is experimental and may change.
.Sp
.Vb 1
\& $type_info_all = $dbh->type_info_all;
.Ve
.Sp
Returns a reference to an array which holds information about each data
type variant supported by the database and driver. The array and its
contents should be treated as read\-only.
.Sp
The first item is a reference to an 'index' hash of \f(CW\*(C`Name =\*(C'\fR> \f(CW\*(C`Index\*(C'\fR pairs.
The items following that are references to arrays, one per supported data
type variant. The leading index hash defines the names and order of the
fields within the arrays that follow it.
For example:
.Sp
.Vb 25
\& $type_info_all = [
\& { TYPE_NAME => 0,
\& DATA_TYPE => 1,
\& COLUMN_SIZE => 2, # was PRECISION originally
\& LITERAL_PREFIX => 3,
\& LITERAL_SUFFIX => 4,
\& CREATE_PARAMS => 5,
\& NULLABLE => 6,
\& CASE_SENSITIVE => 7,
\& SEARCHABLE => 8,
\& UNSIGNED_ATTRIBUTE=> 9,
\& FIXED_PREC_SCALE => 10, # was MONEY originally
\& AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
\& LOCAL_TYPE_NAME => 12,
\& MINIMUM_SCALE => 13,
\& MAXIMUM_SCALE => 14,
\& NUM_PREC_RADIX => 15,
\& },
\& [ 'VARCHAR', SQL_VARCHAR,
\& undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
\& ],
\& [ 'INTEGER', SQL_INTEGER,
\& undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
\& ],
\& ];
.Ve
.Sp
Note that more than one row may have the same value in the \f(CW\*(C`DATA_TYPE\*(C'\fR
field if there are different ways to spell the type name and/or there
are variants of the type with different attributes (e.g., with and
without \f(CW\*(C`AUTO_UNIQUE_VALUE\*(C'\fR set, with and without \f(CW\*(C`UNSIGNED_ATTRIBUTE\*(C'\fR, etc).
.Sp
The rows are ordered by \f(CW\*(C`DATA_TYPE\*(C'\fR first and then by how closely each
type maps to the corresponding \s-1ODBC\s0 \s-1SQL\s0 data type, closest first.
.Sp
The meaning of the fields is described in the documentation for
the \*(L"type_info\*(R" method. The index values shown above (e.g.,
\&\f(CW\*(C`NULLABLE =\*(C'\fR> \f(CW6\fR) are for illustration only. Drivers may define the
fields with a different order.
.Sp
This method is not normally used directly. The \*(L"type_info\*(R" method
provides a more useful interface to the data.
.Sp
Even though an 'index' hash is provided, all the field names in the
index hash defined above will always have the index values defined
above. This is defined behaviour so that you don't need to rely on the
index hash, which is handy because the lettercase of the keys is not
defined. It is usually uppercase, as show here, but drivers are free to
return names with any lettercase. Drivers are also free to return extra
driver-specific columns of information \- though it's recommended that
they start at column index 50 to leave room for expansion of the
\&\s-1DBI/ODBC\s0 specification.
.ie n .IP """type_info""\fR \fI\s-1NEW\s0" 4
.el .IP "\f(CWtype_info\fR \fI\s-1NEW\s0\fR" 4
.IX Item "type_info NEW"
\&\fBWarning:\fR This method is experimental and may change.
.Sp
.Vb 1
\& @type_info = $dbh->type_info($data_type);
.Ve
.Sp
Returns a list of hash references holding information about one or more
variants of \f(CW$data_type\fR. The list is ordered by \f(CW\*(C`DATA_TYPE\*(C'\fR first and
then by how closely each type maps to the corresponding \s-1ODBC\s0 \s-1SQL\s0 data
type, closest first. If called in a scalar context then only the first
(best) element is returned.
.Sp
If \f(CW$data_type\fR is undefined or \f(CW\*(C`SQL_ALL_TYPES\*(C'\fR, then the list will
contain hashes for all data type variants supported by the database and driver.
.Sp
If \f(CW$data_type\fR is an array reference then \f(CW\*(C`type_info\*(C'\fR returns the
information for the \fIfirst\fR type in the array that has any matches.
.Sp
The keys of the hash follow the same letter case conventions as the
rest of the \s-1DBI\s0 (see \*(L"Naming Conventions and Name Space\*(R"). The
following items should exist:
.RS 4
.IP "\s-1TYPE_NAME\s0 (string)" 4
.IX Item "TYPE_NAME (string)"
Data type name for use in \s-1CREATE\s0 \s-1TABLE\s0 statements etc.
.IP "\s-1DATA_TYPE\s0 (integer)" 4
.IX Item "DATA_TYPE (integer)"
\&\s-1SQL\s0 data type number.
.IP "\s-1COLUMN_SIZE\s0 (integer)" 4
.IX Item "COLUMN_SIZE (integer)"
For numeric types, this is either the total number of digits (if the
\&\s-1NUM_PREC_RADIX\s0 value is 10) or the total number of bits allowed in the
column (if \s-1NUM_PREC_RADIX\s0 is 2).
.Sp
For string types, this is the maximum size of the string in bytes.
.Sp
For date and interval types, this is the maximum number of characters
needed to display the value.
.IP "\s-1LITERAL_PREFIX\s0 (string)" 4
.IX Item "LITERAL_PREFIX (string)"
Characters used to prefix a literal. A typical prefix is "\f(CW\*(C`'\*(C'\fR\*(L" for characters,
or possibly \*(R"\f(CW\*(C`0x\*(C'\fR" for binary values passed as hexadecimal. \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is
returned for data types for which this is not applicable.
.IP "\s-1LITERAL_SUFFIX\s0 (string)" 4
.IX Item "LITERAL_SUFFIX (string)"
Characters used to suffix a literal. Typically "\f(CW\*(C`'\*(C'\fR" for characters.
\&\s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned for data types where this is not applicable.
.IP "\s-1CREATE_PARAMS\s0 (string)" 4
.IX Item "CREATE_PARAMS (string)"
Parameter names for data type definition. For example, \f(CW\*(C`CREATE_PARAMS\*(C'\fR for a
\&\f(CW\*(C`DECIMAL\*(C'\fR would be "\f(CW\*(C`precision,scale\*(C'\fR" if the \s-1DECIMAL\s0 type should be
declared as \f(CW\*(C`DECIMAL(\*(C'\fR\fIprecision,scale\fR\f(CW\*(C`)\*(C'\fR where \fIprecision\fR and \fIscale\fR
are integer values. For a \f(CW\*(C`VARCHAR\*(C'\fR it would be "\f(CW\*(C`max length\*(C'\fR".
\&\s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned for data types for which this is not applicable.
.IP "\s-1NULLABLE\s0 (integer)" 4
.IX Item "NULLABLE (integer)"
Indicates whether the data type accepts a \s-1NULL\s0 value:
\&\f(CW0\fR or an empty string = no, \f(CW1\fR = yes, \f(CW2\fR = unknown.
.IP "\s-1CASE_SENSITIVE\s0 (boolean)" 4
.IX Item "CASE_SENSITIVE (boolean)"
Indicates whether the data type is case sensitive in collations and
comparisons.
.IP "\s-1SEARCHABLE\s0 (integer)" 4
.IX Item "SEARCHABLE (integer)"
Indicates how the data type can be used in a \s-1WHERE\s0 clause, as
follows:
.Sp
.Vb 4
\& 0 - Cannot be used in a WHERE clause
\& 1 - Only with a LIKE predicate
\& 2 - All comparison operators except LIKE
\& 3 - Can be used in a WHERE clause with any comparison operator
.Ve
.IP "\s-1UNSIGNED_ATTRIBUTE\s0 (boolean)" 4
.IX Item "UNSIGNED_ATTRIBUTE (boolean)"
Indicates whether the data type is unsigned. \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned
for data types for which this is not applicable.
.IP "\s-1FIXED_PREC_SCALE\s0 (boolean)" 4
.IX Item "FIXED_PREC_SCALE (boolean)"
Indicates whether the data type always has the same precision and scale
(such as a money type). \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned for data types
for which
this is not applicable.
.IP "\s-1AUTO_UNIQUE_VALUE\s0 (boolean)" 4
.IX Item "AUTO_UNIQUE_VALUE (boolean)"
Indicates whether a column of this data type is automatically set to a
unique value whenever a new row is inserted. \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned
for data types for which this is not applicable.
.IP "\s-1LOCAL_TYPE_NAME\s0 (string)" 4
.IX Item "LOCAL_TYPE_NAME (string)"
Localized version of the \f(CW\*(C`TYPE_NAME\*(C'\fR for use in dialog with users.
\&\s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned if a localized name is not available (in which
case \f(CW\*(C`TYPE_NAME\*(C'\fR should be used).
.IP "\s-1MINIMUM_SCALE\s0 (integer)" 4
.IX Item "MINIMUM_SCALE (integer)"
The minimum scale of the data type. If a data type has a fixed scale,
then \f(CW\*(C`MAXIMUM_SCALE\*(C'\fR holds the same value. \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned for
data types for which this is not applicable.
.IP "\s-1MAXIMUM_SCALE\s0 (integer)" 4
.IX Item "MAXIMUM_SCALE (integer)"
The maximum scale of the data type. If a data type has a fixed scale,
then \f(CW\*(C`MINIMUM_SCALE\*(C'\fR holds the same value. \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned for
data types for which this is not applicable.
.IP "\s-1SQL_DATA_TYPE\s0 (integer)" 4
.IX Item "SQL_DATA_TYPE (integer)"
This column is the same as the \f(CW\*(C`DATA_TYPE\*(C'\fR column, except for interval
and datetime data types. For interval and datetime data types, the
\&\f(CW\*(C`SQL_DATA_TYPE\*(C'\fR field will return \f(CW\*(C`SQL_INTERVAL\*(C'\fR or \f(CW\*(C`SQL_DATETIME\*(C'\fR, and the
\&\f(CW\*(C`SQL_DATETIME_SUB\*(C'\fR field below will return the subcode for the specific
interval or datetime data type. If this field is \s-1NULL\s0, then the driver
does not support or report on interval or date subtypes.
.IP "\s-1SQL_DATETIME_SUB\s0 (integer)" 4
.IX Item "SQL_DATETIME_SUB (integer)"
For interval or datetime data types, where the \f(CW\*(C`SQL_DATA_TYPE\*(C'\fR field
above is \f(CW\*(C`SQL_INTERVAL\*(C'\fR or \f(CW\*(C`SQL_DATETIME\*(C'\fR, this field will hold the subcode
for the specific interval or datetime data type. Otherwise it will be
\&\s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR).
.IP "\s-1NUM_PREC_RADIX\s0 (integer)" 4
.IX Item "NUM_PREC_RADIX (integer)"
The radix value of the data type. For approximate numeric types,
\&\f(CW\*(C`NUM_PREC_RADIX\*(C'\fR
contains the value 2 and \f(CW\*(C`COLUMN_SIZE\*(C'\fR holds the number of bits. For
exact numeric types, \f(CW\*(C`NUM_PREC_RADIX\*(C'\fR contains the value 10 and \f(CW\*(C`COLUMN_SIZE\*(C'\fR holds
the number of decimal digits. \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) is returned either for data types
for which this is not applicable or if the driver cannot report this information.
.IP "\s-1INTERVAL_PRECISION\s0 (integer)" 4
.IX Item "INTERVAL_PRECISION (integer)"
The interval leading precision for interval types. \s-1NULL\s0 is returned
either for data types for which this is not applicable or if the driver
cannot report this information.
.RE
.RS 4
.Sp
For example, to find the type name for the fields in a select statement
you can do:
.Sp
.Vb 1
\& @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
.Ve
.Sp
Since \s-1DBI\s0 and \s-1ODBC\s0 drivers vary in how they map their types into the
\&\s-1ISO\s0 standard types you may need to search for more than one type.
Here's an example looking for a usable type to store a date:
.Sp
.Vb 1
\& $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
.Ve
.Sp
Similarly, to more reliably find a type to store small integers, you could
use a list starting with \f(CW\*(C`SQL_SMALLINT\*(C'\fR, \f(CW\*(C`SQL_INTEGER\*(C'\fR, \f(CW\*(C`SQL_DECIMAL\*(C'\fR, etc.
.Sp
For more detailed information about these fields and their meanings, you
can refer to:
.Sp
.Vb 1
\& http://msdn.microsoft.com/library/psdk/dasdk/odch6yy7.htm
.Ve
.Sp
If that \s-1URL\s0 ceases to work then use the \s-1MSDN\s0 search facility at
.Sp
.Vb 1
\& http://search.microsoft.com/us/dev/
.Ve
.Sp
and search the \s-1MSDN\s0 Library for \f(CW\*(C`SQLGetTypeInfo returns\*(C'\fR using the exact phrase option.
The link you want will probably just be called \f(CW\*(C`SQLGetTypeInfo\*(C'\fR (there
may be more than one).
.Sp
The individual data types are currently described here:
.Sp
.Vb 1
\& http://msdn.microsoft.com/library/psdk/dasdk/odap8fcj.htm
.Ve
.Sp
If that \s-1URL\s0 ceases to work, or to get more general information, use the
\&\s-1MSDN\s0 search facility as described above and search for \f(CW\*(C`SQL Data Types\*(C'\fR.
.RE
.ie n .IP """quote""" 4
.el .IP "\f(CWquote\fR" 4
.IX Item "quote"
.Vb 2
\& $sql = $dbh->quote($value);
\& $sql = $dbh->quote($value, $data_type);
.Ve
.Sp
Quote a string literal for use as a literal value in an \s-1SQL\s0 statement,
by escaping any special characters (such as quotation marks)
contained within the string and adding the required type of outer
quotation marks.
.Sp
.Vb 2
\& $sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
\& $dbh->quote("Don't");
.Ve
.Sp
For most database types, quote would return \f(CW'Don''t'\fR (including the
outer quotation marks).
.Sp
An undefined \f(CW$value\fR value will be returned as the string \f(CW\*(C`NULL\*(C'\fR (without
quotation marks) to match how NULLs are represented in \s-1SQL\s0.
.Sp
If \f(CW$data_type\fR is supplied, it is used to try to determine the required
quoting behavior by using the information returned by \*(L"type_info\*(R".
As a special case, the standard numeric types are optimized to return
\&\f(CW$value\fR without calling \f(CW\*(C`type_info\*(C'\fR.
.Sp
Quote will probably \fInot\fR be able to deal with all possible input
(such as binary data or data containing newlines), and is not related in
any way with escaping or quoting shell meta\-characters. There is no
need to quote values being used with \*(L"Placeholders and Bind Values\*(R".
.Sh "Database Handle Attributes"
.IX Subsection "Database Handle Attributes"
This section describes attributes specific to database handles.
.PP
Changes to these database handle attributes do not affect any other
existing or future database handles.
.PP
Attempting to set or get the value of an unknown attribute is fatal,
except for private driver-specific attributes (which all have names
starting with a lowercase letter).
.PP
Example:
.PP
.Vb 2
\& $h->{AutoCommit} = ...; # set/write
\& ... = $h->{AutoCommit}; # get/read
.Ve
.ie n .IP """AutoCommit"" (boolean)" 4
.el .IP "\f(CWAutoCommit\fR (boolean)" 4
.IX Item "AutoCommit (boolean)"
If true, then database changes cannot be rolled-back (undone). If false,
then database changes automatically occur within a \*(L"transaction\*(R", which
must either be committed or rolled back using the \f(CW\*(C`commit\*(C'\fR or \f(CW\*(C`rollback\*(C'\fR
methods.
.Sp
Drivers should always default to \f(CW\*(C`AutoCommit\*(C'\fR mode (an unfortunate
choice largely forced on the \s-1DBI\s0 by \s-1ODBC\s0 and \s-1JDBC\s0 conventions.)
.Sp
Attempting to set \f(CW\*(C`AutoCommit\*(C'\fR to an unsupported value is a fatal error.
This is an important feature of the \s-1DBI\s0. Applications that need
full transaction behavior can set \f(CW\*(C`$dbh\-\*(C'\fR>\f(CW\*(C`{AutoCommit} = 0\*(C'\fR (or
set \f(CW\*(C`AutoCommit\*(C'\fR to 0 via \*(L"connect\*(R")
without having to check that the value was assigned successfully.
.Sp
For the purposes of this description, we can divide databases into three
categories:
.Sp
.Vb 3
\& Databases which don't support transactions at all.
\& Databases in which a transaction is always active.
\& Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
.Ve
.Sp
\&\fB* Databases which don't support transactions at all\fR
.Sp
For these databases, attempting to turn \f(CW\*(C`AutoCommit\*(C'\fR off is a fatal error.
\&\f(CW\*(C`commit\*(C'\fR and \f(CW\*(C`rollback\*(C'\fR both issue warnings about being ineffective while
\&\f(CW\*(C`AutoCommit\*(C'\fR is in effect.
.Sp
\&\fB* Databases in which a transaction is always active\fR
.Sp
These are typically mainstream commercial relational databases with
\&\*(L"\s-1ANSI\s0 standard\*(R" transaction behavior.
If \f(CW\*(C`AutoCommit\*(C'\fR is off, then changes to the database won't have any
lasting effect unless \*(L"commit\*(R" is called (but see also
\&\*(L"disconnect\*(R"). If \*(L"rollback\*(R" is called then any changes since the
last commit are undone.
.Sp
If \f(CW\*(C`AutoCommit\*(C'\fR is on, then the effect is the same as if the \s-1DBI\s0
called \f(CW\*(C`commit\*(C'\fR automatically after every successful database
operation. In other words, calling \f(CW\*(C`commit\*(C'\fR or \f(CW\*(C`rollback\*(C'\fR explicitly while
\&\f(CW\*(C`AutoCommit\*(C'\fR is on would be ineffective because the changes would
have already been commited.
.Sp
Changing \f(CW\*(C`AutoCommit\*(C'\fR from off to on should issue a \*(L"commit\*(R" in most drivers.
.Sp
Changing \f(CW\*(C`AutoCommit\*(C'\fR from on to off should have no immediate effect.
.Sp
For databases which don't support a specific auto-commit mode, the
driver has to commit each statement automatically using an explicit
\&\f(CW\*(C`COMMIT\*(C'\fR after it completes successfully (and roll it back using an
explicit \f(CW\*(C`ROLLBACK\*(C'\fR if it fails). The error information reported to the
application will correspond to the statement which was executed, unless
it succeeded and the commit or rollback failed.
.Sp
\&\fB* Databases in which a transaction must be explicitly started\fR
.Sp
For these databases, the intention is to have them act like databases in
which a transaction is always active (as described above).
.Sp
To do this, the \s-1DBI\s0 driver will automatically begin a transaction when
\&\f(CW\*(C`AutoCommit\*(C'\fR is turned off (from the default \*(L"on\*(R" state) and will
automatically begin another transaction after a \*(L"commit\*(R" or \*(L"rollback\*(R".
In this way, the application does not have to treat these databases as a
special case.
.Sp
See \*(L"commit\*(R", \*(L"disconnect\*(R" and \*(L"Transactions\*(R" for other important
notes about transactions.
.ie n .IP """Driver"" (handle)" 4
.el .IP "\f(CWDriver\fR (handle)" 4
.IX Item "Driver (handle)"
Holds the handle of the parent driver. The only recommended use for this
is to find the name of the driver using:
.Sp
.Vb 1
\& $dbh->{Driver}->{Name}
.Ve
.ie n .IP """Name"" (string)" 4
.el .IP "\f(CWName\fR (string)" 4
.IX Item "Name (string)"
Holds the \*(L"name\*(R" of the database. Usually (and recommended to be) the
same as the "\f(CW\*(C`dbi:DriverName:...\*(C'\fR\*(L" string used to connect to the database,
but with the leading \*(R"\f(CW\*(C`dbi:DriverName:\*(C'\fR" removed.
.ie n .IP """Statement"" (string, read\-only)" 4
.el .IP "\f(CWStatement\fR (string, read\-only)" 4
.IX Item "Statement (string, read-only)"
Returns the statement string passed to the most recent \*(L"prepare\*(R" method
called in this database handle, even if that method failed. This is especially
useful where \f(CW\*(C`RaiseError\*(C'\fR is enabled and the exception handler checks $@
and sees that a 'prepare' method call failed.
.ie n .IP """RowCacheSize"" (integer)" 4
.el .IP "\f(CWRowCacheSize\fR (integer)" 4
.IX Item "RowCacheSize (integer)"
A hint to the driver indicating the size of the local row cache that the
application would like the driver to use for future \f(CW\*(C`SELECT\*(C'\fR statements.
If a row cache is not implemented, then setting \f(CW\*(C`RowCacheSize\*(C'\fR is ignored
and getting the value returns \f(CW\*(C`undef\*(C'\fR.
.Sp
Some \f(CW\*(C`RowCacheSize\*(C'\fR values have special meaning, as follows:
.Sp
.Vb 4
\& 0 - Automatically determine a reasonable cache size for each C<SELECT>
\& 1 - Disable the local row cache
\& >1 - Cache this many rows
\& <0 - Cache as many rows that will fit into this much memory for each C<SELECT>.
.Ve
.Sp
Note that large cache sizes may require a very large amount of memory
(\fIcached rows * maximum size of row\fR). Also, a large cache will cause
a longer delay not only for the first fetch, but also whenever the
cache needs refilling.
.Sp
See also the \*(L"RowsInCache\*(R" statement handle attribute.
.SH "DBI STATEMENT HANDLE OBJECTS"
.IX Header "DBI STATEMENT HANDLE OBJECTS"
This section lists the methods and attributes associated with \s-1DBI\s0
statement handles.
.Sh "Statement Handle Methods"
.IX Subsection "Statement Handle Methods"
The \s-1DBI\s0 defines the following methods for use on \s-1DBI\s0 statement handles:
.ie n .IP """bind_param""" 4
.el .IP "\f(CWbind_param\fR" 4
.IX Item "bind_param"
.Vb 3
\& $rc = $sth->bind_param($p_num, $bind_value) or die $sth->errstr;
\& $rv = $sth->bind_param($p_num, $bind_value, \e%attr) or ...
\& $rv = $sth->bind_param($p_num, $bind_value, $bind_type) or ...
.Ve
.Sp
The \f(CW\*(C`bind_param\*(C'\fR method can be used to bind a value
with a placeholder embedded in the prepared statement. Placeholders
are indicated with question mark character (\f(CW\*(C`?\*(C'\fR). For example:
.Sp
.Vb 5
\& $dbh->{RaiseError} = 1; # save having to check each method call
\& $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?");
\& $sth->bind_param(1, "John%"); # placeholders are numbered from 1
\& $sth->execute;
\& DBI::dump_results($sth);
.Ve
.Sp
Note that the \f(CW\*(C`?\*(C'\fR is not enclosed in quotation marks, even when the
placeholder represents a string. Some drivers also allow placeholders
like \f(CW\*(C`:\*(C'\fR\fIname\fR and \f(CW\*(C`:\*(C'\fR\fIn\fR (e.g., \f(CW\*(C`:1\*(C'\fR, \f(CW\*(C`:2\*(C'\fR, and so on)
in addition to \f(CW\*(C`?\*(C'\fR, but their use
is not portable. Undefined bind values or \f(CW\*(C`undef\*(C'\fR can be used to
indicate null values.
.Sp
Some drivers do not support placeholders.
.Sp
With most drivers, placeholders can't be used for any element of a
statement that would prevent the database server from validating the
statement and creating a query execution plan for it. For example:
.Sp
.Vb 2
\& "SELECT name, age FROM ?" # wrong (will probably fail)
\& "SELECT name, ? FROM people" # wrong (but may not 'fail')
.Ve
.Sp
Also, placeholders can only represent single scalar values.
For example, the following
statement won't work as expected for more than one value:
.Sp
.Vb 1
\& "SELECT name, age FROM people WHERE name IN (?)" # wrong
.Ve
.Sp
\&\fBData Types for Placeholders\fR
.Sp
The \f(CW\*(C`\e%attr\*(C'\fR parameter can be used to hint at the data type the
placeholder should have. Typically, the driver is only interested in
knowing if the placeholder should be bound as a number or a string.
.Sp
.Vb 1
\& $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
.Ve
.Sp
As a short-cut for this common case, the data type can be passed
directly, in place of the \f(CW\*(C`\e%attr\*(C'\fR hash reference. This example is
equivalent to the one above:
.Sp
.Vb 1
\& $sth->bind_param(1, $value, SQL_INTEGER);
.Ve
.Sp
The \f(CW\*(C`TYPE\*(C'\fR value indicates the standard (non\-driver\-specific) type for
this parameter. To specify the driver-specific type, the driver may
support a driver-specific attribute, such as \f(CW\*(C`{ ora_type =\*(C'\fR>\f(CW\*(C` 97 }\*(C'\fR. The
data type for a placeholder cannot be changed after the first
\&\f(CW\*(C`bind_param\*(C'\fR call. However, it can be left unspecified, in which case it
defaults to the previous value.
.Sp
The \s-1SQL_INTEGER\s0 and other related constants can be imported using
.Sp
.Vb 1
\& use DBI qw(:sql_types);
.Ve
.Sp
See \*(L"\s-1DBI\s0 Constants\*(R" for more information.
.Sp
Perl only has string and number scalar data types. All database types
that aren't numbers are bound as strings and must be in a format the
database will understand.
.Sp
As an alternative to specifying the data type in the \f(CW\*(C`bind_param\*(C'\fR call,
you can let the driver pass the value as the default type (\f(CW\*(C`VARCHAR\*(C'\fR).
You can then use an \s-1SQL\s0 function to convert the type within the statement.
For example:
.Sp
.Vb 1
\& INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
.Ve
.Sp
The \f(CW\*(C`CONVERT\*(C'\fR function used here is just an example. The actual function
and syntax will vary between different databases and is non\-portable.
.Sp
See also \*(L"Placeholders and Bind Values\*(R" for more information.
.ie n .IP """bind_param_inout""" 4
.el .IP "\f(CWbind_param_inout\fR" 4
.IX Item "bind_param_inout"
.Vb 3
\& $rc = $sth->bind_param_inout($p_num, \e$bind_value, $max_len) or die $sth->errstr;
\& $rv = $sth->bind_param_inout($p_num, \e$bind_value, $max_len, \e%attr) or ...
\& $rv = $sth->bind_param_inout($p_num, \e$bind_value, $max_len, $bind_type) or ...
.Ve
.Sp
This method acts like \*(L"bind_param\*(R", but also enables values to be
updated by the statement. The statement is typically
a call to a stored procedure. The \f(CW$bind_value\fR must be passed as a
reference to the actual value to be used.
.Sp
Note that unlike \*(L"bind_param\*(R", the \f(CW$bind_value\fR variable is not
read when \f(CW\*(C`bind_param_inout\*(C'\fR is called. Instead, the value in the
variable is read at the time \*(L"execute\*(R" is called.
.Sp
The additional \f(CW$max_len\fR parameter specifies the minimum amount of
memory to allocate to \f(CW$bind_value\fR for the new value. If the value
returned from the database is too
big to fit, then the execution should fail. If unsure what value to use,
pick a generous length, i.e., a length larger than the longest value that would ever be
returned. The only cost of using a larger value than needed is wasted memory.
.Sp
It is expected that few drivers will support this method. The only
driver currently known to do so is DBD::Oracle (\s-1DBD::ODBC\s0 may support
it in a future release). Therefore it should not be used for database
independent applications.
.Sp
Undefined values or \f(CW\*(C`undef\*(C'\fR are used to indicate null values.
See also \*(L"Placeholders and Bind Values\*(R" for more information.
.ie n .IP """execute""" 4
.el .IP "\f(CWexecute\fR" 4
.IX Item "execute"
.Vb 2
\& $rv = $sth->execute or die $sth->errstr;
\& $rv = $sth->execute(@bind_values) or die $sth->errstr;
.Ve
.Sp
Perform whatever processing is necessary to execute the prepared
statement. An \f(CW\*(C`undef\*(C'\fR is returned if an error occurs. A successful
\&\f(CW\*(C`execute\*(C'\fR always returns true regardless of the number of rows affected,
even if it's zero (see below). It is always important to check the
return status of \f(CW\*(C`execute\*(C'\fR (and most other \s-1DBI\s0 methods) for errors.
.Sp
For a \fInon\fR\-\f(CW\*(C`SELECT\*(C'\fR statement, \f(CW\*(C`execute\*(C'\fR returns the number of rows
affected, if known. If no rows were affected, then \f(CW\*(C`execute\*(C'\fR returns
"\f(CW0E0\fR", which Perl will treat as 0 but will regard as true. Note that it
is \fInot\fR an error for no rows to be affected by a statement. If the
number of rows affected is not known, then \f(CW\*(C`execute\*(C'\fR returns \-1.
.Sp
For \f(CW\*(C`SELECT\*(C'\fR statements, execute simply \*(L"starts\*(R" the query within the
database engine. Use one of the fetch methods to retreive the data after
calling \f(CW\*(C`execute\*(C'\fR. The \f(CW\*(C`execute\*(C'\fR method does \fInot\fR return the number of
rows that will be returned by the query (because most databases can't
tell in advance), it simply returns a true value.
.Sp
If any arguments are given, then \f(CW\*(C`execute\*(C'\fR will effectively call
\&\*(L"bind_param\*(R" for each value before executing the statement.
Values bound in this way are usually treated as \f(CW\*(C`SQL_VARCHAR\*(C'\fR types
unless the driver can determine the correct type (which is rare), or
unless
\&\f(CW\*(C`bind_param\*(C'\fR (or \f(CW\*(C`bind_param_inout\*(C'\fR) has already been used to specify the
type.
.ie n .IP """fetchrow_arrayref""" 4
.el .IP "\f(CWfetchrow_arrayref\fR" 4
.IX Item "fetchrow_arrayref"
.Vb 2
\& $ary_ref = $sth->fetchrow_arrayref;
\& $ary_ref = $sth->fetch; # alias
.Ve
.Sp
Fetches the next row of data and returns a reference to an array
holding the field values. Null fields are returned as \f(CW\*(C`undef\*(C'\fR
values in the array.
This is the fastest way to fetch data, particularly if used with
\&\f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`bind_columns\*(C'\fR.
.Sp
If there are no more rows or if an error occurs, then \f(CW\*(C`fetchrow_arrayref\*(C'\fR
returns an \f(CW\*(C`undef\*(C'\fR. You should check \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`err\*(C'\fR afterwards (or use the
\&\f(CW\*(C`RaiseError\*(C'\fR attribute) to discover if the \f(CW\*(C`undef\*(C'\fR returned was due to an
error.
.Sp
Note that the same array reference is returned for each fetch, so don't
store the reference and then use it after a later fetch. Also, the
elements of the array are also reused for each row, so take care if you
want to take a reference to an element. See also \*(L"bind_columns\*(R".
.ie n .IP """fetchrow_array""" 4
.el .IP "\f(CWfetchrow_array\fR" 4
.IX Item "fetchrow_array"
.Vb 1
\& @ary = $sth->fetchrow_array;
.Ve
.Sp
An alternative to \f(CW\*(C`fetchrow_arrayref\*(C'\fR. Fetches the next row of data
and returns it as a list containing the field values. Null fields
are returned as \f(CW\*(C`undef\*(C'\fR values in the list.
.Sp
If there are no more rows or if an error occurs, then \f(CW\*(C`fetchrow_array\*(C'\fR
returns an empty list. You should check \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`err\*(C'\fR afterwards (or use
the \f(CW\*(C`RaiseError\*(C'\fR attribute) to discover if the empty list returned was
due to an error.
.Sp
In a scalar context, \f(CW\*(C`fetchrow_array\*(C'\fR returns the value of the first
field. An \f(CW\*(C`undef\*(C'\fR is returned if there are no more rows or if an error
occurred. Since that \f(CW\*(C`undef\*(C'\fR can't be distinguished from an \f(CW\*(C`undef\*(C'\fR returned
because the first field value was \s-1NULL\s0, you should exercise some
caution if you use \f(CW\*(C`fetchrow_array\*(C'\fR in a scalar context.
.ie n .IP """fetchrow_hashref""" 4
.el .IP "\f(CWfetchrow_hashref\fR" 4
.IX Item "fetchrow_hashref"
.Vb 2
\& $hash_ref = $sth->fetchrow_hashref;
\& $hash_ref = $sth->fetchrow_hashref($name);
.Ve
.Sp
An alternative to \f(CW\*(C`fetchrow_arrayref\*(C'\fR. Fetches the next row of data
and returns it as a reference to a hash containing field name and field
value pairs. Null fields are returned as \f(CW\*(C`undef\*(C'\fR values in the hash.
.Sp
If there are no more rows or if an error occurs, then \f(CW\*(C`fetchrow_hashref\*(C'\fR
returns an \f(CW\*(C`undef\*(C'\fR. You should check \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`err\*(C'\fR afterwards (or use the
\&\f(CW\*(C`RaiseError\*(C'\fR attribute) to discover if the \f(CW\*(C`undef\*(C'\fR returned was due to an
error.
.Sp
The optional \f(CW$name\fR parameter specifies the name of the statement handle
attribute. For historical reasons it defaults to "\f(CW\*(C`NAME\*(C'\fR\*(L", however using either
\&\*(R"\f(CW\*(C`NAME_lc\*(C'\fR\*(L" or \*(R"\f(CW\*(C`NAME_uc\*(C'\fR" is recomended for portability.
.Sp
The keys of the hash are the same names returned by \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`{$name}\*(C'\fR. If
more than one field has the same name, there will only be one entry in
the returned hash for those fields.
.Sp
Because of the extra work \f(CW\*(C`fetchrow_hashref\*(C'\fR and Perl have to perform, it
is not as efficient as \f(CW\*(C`fetchrow_arrayref\*(C'\fR or \f(CW\*(C`fetchrow_array\*(C'\fR.
.Sp
Currently, a new hash reference is returned for each row. \fIThis will
change\fR in the future to return the same hash ref each time, so don't
rely on the current behaviour.
.ie n .IP """fetchall_arrayref""" 4
.el .IP "\f(CWfetchall_arrayref\fR" 4
.IX Item "fetchall_arrayref"
.Vb 3
\& $tbl_ary_ref = $sth->fetchall_arrayref;
\& $tbl_ary_ref = $sth->fetchall_arrayref( $slice_array_ref );
\& $tbl_ary_ref = $sth->fetchall_arrayref( $slice_hash_ref );
.Ve
.Sp
The \f(CW\*(C`fetchall_arrayref\*(C'\fR method can be used to fetch all the data to be
returned from a prepared and executed statement handle. It returns a
reference to an array that contains one reference per row.
.Sp
If there are no rows to return, \f(CW\*(C`fetchall_arrayref\*(C'\fR returns a reference
to an empty array. If an error occurs, \f(CW\*(C`fetchall_arrayref\*(C'\fR returns the
data fetched thus far, which may be none. You should check \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`err\*(C'\fR
afterwards (or use the \f(CW\*(C`RaiseError\*(C'\fR attribute) to discover if the data is
complete or was truncated due to an error.
.Sp
When passed an array reference, \f(CW\*(C`fetchall_arrayref\*(C'\fR uses \*(L"fetchrow_arrayref\*(R"
to fetch each row as an array ref. If the parameter array is not empty
then it is used as a slice to select individual columns by index number.
.Sp
With no parameters, \f(CW\*(C`fetchall_arrayref\*(C'\fR acts as if passed an empty array ref.
.Sp
When passed a hash reference, \f(CW\*(C`fetchall_arrayref\*(C'\fR uses \*(L"fetchrow_hashref\*(R"
to fetch each row as a hash reference. If the parameter hash is empty then
fetchrow_hashref is simply called in a tight loop and the keys in the hashes
have whatever name lettercase is returned by default from fetchrow_hashref.
.Sp
If the parameter hash is not empty, then it is used as a slice to
select individual columns by name. The names should be lower case
regardless of the letter case in \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`{NAME}\*(C'\fR. The values of
the hash should be set to 1.
.Sp
For example, to fetch just the first column of every row:
.Sp
.Vb 1
\& $tbl_ary_ref = $sth->fetchall_arrayref([0]);
.Ve
.Sp
To fetch the second to last and last column of every row:
.Sp
.Vb 1
\& $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
.Ve
.Sp
To fetch all fields of every row as a hash ref:
.Sp
.Vb 1
\& $tbl_ary_ref = $sth->fetchall_arrayref({});
.Ve
.Sp
To fetch only the fields called \*(L"foo\*(R" and \*(L"bar\*(R" of every row as a hash ref:
.Sp
.Vb 1
\& $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, bar=>1 });
.Ve
.Sp
The first two examples return a reference to an array of array refs. The last
returns a reference to an array of hash refs.
.ie n .IP """fetchall_hashref""" 4
.el .IP "\f(CWfetchall_hashref\fR" 4
.IX Item "fetchall_hashref"
.Vb 1
\& $tbl_ary_ref = $sth->fetchall_hashref;
.Ve
.Sp
The \f(CW\*(C`fetchall_hashref\*(C'\fR method can be used to fetch all the data to be
returned from a prepared and executed statement handle. It returns a
reference to an array that contains one hash of field name and value
pairs per row.
.Sp
If there are no rows to return, \f(CW\*(C`fetchall_hashref\*(C'\fR returns a reference
to an empty array. If an error occurs, \f(CW\*(C`fetchall_hashref\*(C'\fR returns the
data fetched thus far, which may be none. You should check \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`err\*(C'\fR
afterwards (or use the \f(CW\*(C`RaiseError\*(C'\fR attribute) to discover if the data is
complete or was truncated due to an error.
.ie n .IP """finish""" 4
.el .IP "\f(CWfinish\fR" 4
.IX Item "finish"
.Vb 1
\& $rc = $sth->finish;
.Ve
.Sp
Indicates that no more data will be fetched from this statement handle
before it is either executed again or destroyed. The \f(CW\*(C`finish\*(C'\fR method
is rarely needed, but can sometimes be helpful in very specific
situations to allow the server to free up resources (such as sort
buffers).
.Sp
When all the data has been fetched from a \f(CW\*(C`SELECT\*(C'\fR statement, the driver
should automatically call \f(CW\*(C`finish\*(C'\fR for you. So you should not normally
need to call it explicitly.
.Sp
Consider a query like:
.Sp
.Vb 1
\& SELECT foo FROM table WHERE bar=? ORDER BY foo
.Ve
.Sp
where you want to select just the first (smallest) \*(L"foo\*(R" value from a
very large table. When executed, the database server will have to use
temporary buffer space to store the sorted rows. If, after executing
the handle and selecting one row, the handle won't be re-executed for
some time and won't be destroyed, the \f(CW\*(C`finish\*(C'\fR method can be used to tell
the server that the buffer space can be freed.
.Sp
Calling \f(CW\*(C`finish\*(C'\fR resets the \*(L"Active\*(R" attribute for the statement. It
may also make some statement handle attributes (such as \f(CW\*(C`NAME\*(C'\fR and \f(CW\*(C`TYPE\*(C'\fR)
unavailable if they have not already been accessed (and thus cached).
.Sp
The \f(CW\*(C`finish\*(C'\fR method does not affect the transaction status of the
database connection. It has nothing to do with transactions. It's mostly an
internal \*(L"housekeeping\*(R" method that is rarely needed. There's no need
to call \f(CW\*(C`finish\*(C'\fR if you're about to destroy or re-execute the statement
handle. See also \*(L"disconnect\*(R" and the \*(L"Active\*(R" attribute.
.Sp
The \f(CW\*(C`finish\*(C'\fR method should have been called \f(CW\*(C`cancel_select\*(C'\fR.
.ie n .IP """rows""" 4
.el .IP "\f(CWrows\fR" 4
.IX Item "rows"
.Vb 1
\& $rv = $sth->rows;
.Ve
.Sp
Returns the number of rows affected by the last row affecting command,
or \-1 if the number of rows is not known or not available.
.Sp
Generally, you can only rely on a row count after a \fInon\fR\-\f(CW\*(C`SELECT\*(C'\fR
\&\f(CW\*(C`execute\*(C'\fR (for some specific operations like \f(CW\*(C`UPDATE\*(C'\fR and \f(CW\*(C`DELETE\*(C'\fR), or
after fetching all the rows of a \f(CW\*(C`SELECT\*(C'\fR statement.
.Sp
For \f(CW\*(C`SELECT\*(C'\fR statements, it is generally not possible to know how many
rows will be returned except by fetching them all. Some drivers will
return the number of rows the application has fetched so far, but
others may return \-1 until all rows have been fetched. So use of the
\&\f(CW\*(C`rows\*(C'\fR method or \f(CW$DBI::rows\fR with \f(CW\*(C`SELECT\*(C'\fR statements is not
recommended.
.Sp
One alternative method to get a row count for a \f(CW\*(C`SELECT\*(C'\fR is to execute a
\&\*(L"\s-1SELECT\s0 \s-1COUNT\s0(*) \s-1FROM\s0 ...\*(R" \s-1SQL\s0 statement with the same \*(L"...\*(R" as your
query and then fetch the row count from that.
.ie n .IP """bind_col""" 4
.el .IP "\f(CWbind_col\fR" 4
.IX Item "bind_col"
.Vb 1
\& $rc = $sth->bind_col($column_number, \e$var_to_bind);
.Ve
.Sp
Binds an output column (field) of a \f(CW\*(C`SELECT\*(C'\fR statement to a Perl variable.
See \f(CW\*(C`bind_columns\*(C'\fR below for an example. Note that column numbers count
up from 1.
.Sp
Whenever a row is fetched from the database, the corresponding Perl
variable is automatically updated. There is no need to fetch and assign
the values manually. The binding is performed at a very low level
using Perl aliasing so there is no extra copying taking place. This
makes using bound variables very efficient.
.Sp
For maximum portability between drivers, \f(CW\*(C`bind_col\*(C'\fR should be called after
\&\f(CW\*(C`execute\*(C'\fR. This restriction may be removed in a later version of the \s-1DBI\s0.
.Sp
You do not need to bind output columns in order to fetch data, but it
can be useful for some applications which need either maximum performance
or greater clarity of code. The \*(L"bind_param\*(R" method
performs a similar but opposite function for input variables.
.ie n .IP """bind_columns""" 4
.el .IP "\f(CWbind_columns\fR" 4
.IX Item "bind_columns"
.Vb 1
\& $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
.Ve
.Sp
Calls \*(L"bind_col\*(R" for each column of the \f(CW\*(C`SELECT\*(C'\fR statement.
The \f(CW\*(C`bind_columns\*(C'\fR method will die if the number of references does not
match the number of fields.
.Sp
For maximum portability between drivers, \f(CW\*(C`bind_columns\*(C'\fR should be called
after \f(CW\*(C`execute\*(C'\fR.
.Sp
For example:
.Sp
.Vb 4
\& $dbh->{RaiseError} = 1; # do this, or check every call for errors
\& $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
\& $sth->execute;
\& my ($region, $sales);
.Ve
.Sp
.Vb 2
\& # Bind Perl variables to columns:
\& $rv = $sth->bind_columns(\e$region, \e$sales);
.Ve
.Sp
.Vb 2
\& # you can also use Perl's \e(...) syntax (see perlref docs):
\& # $sth->bind_columns(\e($region, $sales));
.Ve
.Sp
.Vb 4
\& # Column binding is the most efficient way to fetch data
\& while ($sth->fetch) {
\& print "$region: $sales\en";
\& }
.Ve
.Sp
For compatibility with old scripts, the first parameter will be
ignored if it is \f(CW\*(C`undef\*(C'\fR or a hash reference.
.Sp
Here's a more fancy example that binds columns to the values \fIinside\fR
a hash (thanks to H.Merijn Brand):
.Sp
.Vb 6
\& $sth->execute;
\& my %row;
\& $sth->bind_columns( \e( @row{ @{$sth->{NAME_lc} } } ));
\& while ($sth->fetch) {
\& print "$row{region}: $row{sales}\en";
\& }
.Ve
.ie n .IP """dump_results""" 4
.el .IP "\f(CWdump_results\fR" 4
.IX Item "dump_results"
.Vb 1
\& $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
.Ve
.Sp
Fetches all the rows from \f(CW$sth\fR, calls \f(CW\*(C`DBI::neat_list\*(C'\fR for each row, and
prints the results to \f(CW$fh\fR (defaults to \f(CW\*(C`STDOUT\*(C'\fR) separated by \f(CW$lsep\fR
(default \f(CW"\en"\fR). \f(CW$fsep\fR defaults to \f(CW", "\fR and \f(CW$maxlen\fR defaults to 35.
.Sp
This method is designed as a handy utility for prototyping and
testing queries. Since it uses \*(L"neat_list\*(R" to
format and edit the string for reading by humans, it is not recomended
for data transfer applications.
.Sh "Statement Handle Attributes"
.IX Subsection "Statement Handle Attributes"
This section describes attributes specific to statement handles. Most
of these attributes are read\-only.
.PP
Changes to these statement handle attributes do not affect any other
existing or future statement handles.
.PP
Attempting to set or get the value of an unknown attribute is fatal,
except for private driver specific attributes (which all have names
starting with a lowercase letter).
.PP
Example:
.PP
.Vb 1
\& ... = $h->{NUM_OF_FIELDS}; # get/read
.Ve
.PP
Note that some drivers cannot provide valid values for some or all of
these attributes until after \f(CW\*(C`$sth\-\*(C'\fR>\f(CW\*(C`execute\*(C'\fR has been called.
.PP
See also \*(L"finish\*(R" to learn more about the effect it
may have on some attributes.
.ie n .IP """NUM_OF_FIELDS"" (integer, read\-only)" 4
.el .IP "\f(CWNUM_OF_FIELDS\fR (integer, read\-only)" 4
.IX Item "NUM_OF_FIELDS (integer, read-only)"
Number of fields (columns) the prepared statement will return. Non\-\f(CW\*(C`SELECT\*(C'\fR
statements will have \f(CW\*(C`NUM_OF_FIELDS == 0\*(C'\fR.
.ie n .IP """NUM_OF_PARAMS"" (integer, read\-only)" 4
.el .IP "\f(CWNUM_OF_PARAMS\fR (integer, read\-only)" 4
.IX Item "NUM_OF_PARAMS (integer, read-only)"
The number of parameters (placeholders) in the prepared statement.
See \s-1SUBSTITUTION\s0 \s-1VARIABLES\s0 below for more details.
.ie n .IP """NAME"" (array\-ref, read\-only)" 4
.el .IP "\f(CWNAME\fR (array\-ref, read\-only)" 4
.IX Item "NAME (array-ref, read-only)"
Returns a reference to an array of field names for each column. The
names may contain spaces but should not be truncated or have any
trailing space. Note that the names have the letter case (upper, lower
or mixed) as returned by the driver being used. Portable applications
should use \*(L"NAME_lc\*(R" or \*(L"NAME_uc\*(R".
.Sp
.Vb 1
\& print "First column name: $sth->{NAME}->[0]\en";
.Ve
.ie n .IP """NAME_lc"" (array\-ref, read\-only)" 4
.el .IP "\f(CWNAME_lc\fR (array\-ref, read\-only)" 4
.IX Item "NAME_lc (array-ref, read-only)"
Like \*(L"\s-1NAME\s0\*(R" but always returns lowercase names.
.ie n .IP """NAME_uc"" (array\-ref, read\-only)" 4
.el .IP "\f(CWNAME_uc\fR (array\-ref, read\-only)" 4
.IX Item "NAME_uc (array-ref, read-only)"
Like \*(L"\s-1NAME\s0\*(R" but always returns uppercase names.
.ie n .IP """TYPE"" (array\-ref, read\-only)" 4
.el .IP "\f(CWTYPE\fR (array\-ref, read\-only)" 4
.IX Item "TYPE (array-ref, read-only)"
Returns a reference to an array of integer values for each
column. The value indicates the data type of the corresponding column.
.Sp
The values correspond to the international standards (\s-1ANSI\s0 X3.135
and \s-1ISO/IEC\s0 9075) which, in general terms, means \s-1ODBC\s0. Driver-specific
types that don't exactly match standard types should generally return
the same values as an \s-1ODBC\s0 driver supplied by the makers of the
database. That might include private type numbers in ranges the vendor
has officially registered with the \s-1ISO\s0 working group:
.Sp
.Vb 1
\& ftp://jerry.ece.umassd.edu/isowg3/dbl/SQL_Registry
.Ve
.Sp
Where there's no vendor-supplied \s-1ODBC\s0 driver to be compatible with, the
\&\s-1DBI\s0 driver can use type numbers in the range that is now officially reserved
for use by the \s-1DBI:\s0 \-9999 to \-9000.
.Sp
All possible values for \f(CW\*(C`TYPE\*(C'\fR should have at least one entry in the
output of the \f(CW\*(C`type_info_all\*(C'\fR method (see \*(L"type_info_all\*(R").
.ie n .IP """PRECISION"" (array\-ref, read\-only)" 4
.el .IP "\f(CWPRECISION\fR (array\-ref, read\-only)" 4
.IX Item "PRECISION (array-ref, read-only)"
Returns a reference to an array of integer values for each
column. For non-numeric columns, the value generally refers to either
the maximum length or the defined length of the column. For numeric
columns, the value refers to the maximum number of significant digits
used by the data type (without considering a sign character or decimal
point). Note that for floating point types (\s-1REAL\s0, \s-1FLOAT\s0, \s-1DOUBLE\s0), the
\&\*(L"display size\*(R" can be up to 7 characters greater than the precision.
(for the sign + decimal point + the letter E + a sign + 2 or 3 digits).
.ie n .IP """SCALE"" (array\-ref, read\-only)" 4
.el .IP "\f(CWSCALE\fR (array\-ref, read\-only)" 4
.IX Item "SCALE (array-ref, read-only)"
Returns a reference to an array of integer values for each column.
\&\s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) values indicate columns where scale is not applicable.
.ie n .IP """NULLABLE"" (array\-ref, read\-only)" 4
.el .IP "\f(CWNULLABLE\fR (array\-ref, read\-only)" 4
.IX Item "NULLABLE (array-ref, read-only)"
Returns a reference to an array indicating the possibility of each
column returning a null. Possible values are \f(CW0\fR
(or an empty string) = no, \f(CW1\fR = yes, \f(CW2\fR = unknown.
.Sp
.Vb 1
\& print "First column may return NULL\en" if $sth->{NULLABLE}->[0];
.Ve
.ie n .IP """CursorName"" (string, read\-only)" 4
.el .IP "\f(CWCursorName\fR (string, read\-only)" 4
.IX Item "CursorName (string, read-only)"
Returns the name of the cursor associated with the statement handle, if
available. If not available or if the database driver does not support the
\&\f(CW"where current of ..."\fR \s-1SQL\s0 syntax, then it returns \f(CW\*(C`undef\*(C'\fR.
.ie n .IP """Statement"" (string, read\-only)" 4
.el .IP "\f(CWStatement\fR (string, read\-only)" 4
.IX Item "Statement (string, read-only)"
Returns the statement string passed to the \*(L"prepare\*(R" method.
.ie n .IP """RowsInCache"" (integer, read\-only)" 4
.el .IP "\f(CWRowsInCache\fR (integer, read\-only)" 4
.IX Item "RowsInCache (integer, read-only)"
If the driver supports a local row cache for \f(CW\*(C`SELECT\*(C'\fR statements, then
this attribute holds the number of un-fetched rows in the cache. If the
driver doesn't, then it returns \f(CW\*(C`undef\*(C'\fR. Note that some drivers pre-fetch
rows on execute, whereas others wait till the first fetch.
.Sp
See also the \*(L"RowCacheSize\*(R" database handle attribute.
.SH "FURTHER INFORMATION"
.IX Header "FURTHER INFORMATION"
.Sh "Transactions"
.IX Subsection "Transactions"
Transactions are a fundamental part of any robust database system. They
protect against errors and database corruption by ensuring that sets of
related changes to the database take place in atomic (indivisible,
all\-or\-nothing) units.
.PP
This section applies to databases that support transactions and where
\&\f(CW\*(C`AutoCommit\*(C'\fR is off. See \*(L"AutoCommit\*(R" for details of using \f(CW\*(C`AutoCommit\*(C'\fR
with various types of databases.
.PP
The recommended way to implement robust transactions in Perl
applications is to use \f(CW\*(C`RaiseError\*(C'\fR and \f(CW\*(C`eval\ {\ ...\ }\*(C'\fR
(which is very fast, unlike \f(CW\*(C`eval\ "..."\*(C'\fR). For example:
.PP
.Vb 13
\& $dbh->{AutoCommit} = 0; # enable transactions, if possible
\& $dbh->{RaiseError} = 1;
\& eval {
\& foo(...) # do lots of work here
\& bar(...) # including inserts
\& baz(...) # and updates
\& $dbh->commit; # commit the changes if we get this far
\& };
\& if ($@) {
\& warn "Transaction aborted because $@";
\& $dbh->rollback; # undo the incomplete changes
\& # add other application on-error-clean-up code here
\& }
.Ve
.PP
If the \f(CW\*(C`RaiseError\*(C'\fR attribute is not set, then \s-1DBI\s0 calls would need to be
manually checked for errors, typically like this:
.PP
.Vb 1
\& $h->method(@args) or die $h->errstr;
.Ve
.PP
With \f(CW\*(C`RaiseError\*(C'\fR set, the \s-1DBI\s0 will automatically \f(CW\*(C`die\*(C'\fR if any \s-1DBI\s0 method
call on that handle (or a child handle) fails, so you don't have to
test the return value of each method call. See \*(L"RaiseError\*(R" for more
details.
.PP
A major advantage of the \f(CW\*(C`eval\*(C'\fR approach is that the transaction will be
properly rolled back if \fIany\fR code (not just \s-1DBI\s0 calls) in the inner
application dies for any reason. The major advantage of using the
\&\f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`{RaiseError}\*(C'\fR attribute is that all \s-1DBI\s0 calls will be checked
automatically. Both techniques are strongly recommended.
.PP
After calling \f(CW\*(C`commit\*(C'\fR or \f(CW\*(C`rollback\*(C'\fR many drivers will not let you
fetch from a previously active \f(CW\*(C`SELECT\*(C'\fR statement handle that's a child
of the same database handle. A typical way round this is to connect the
the database twice and use one connection for \f(CW\*(C`SELECT\*(C'\fR statements.
.Sh "Handling \s-1BLOB\s0 / \s-1LONG\s0 / Memo Fields"
.IX Subsection "Handling BLOB / LONG / Memo Fields"
Many databases support \*(L"blob\*(R" (binary large objects), \*(L"long\*(R", or similar
datatypes for holding very long strings or large amounts of binary
data in a single field. Some databases support variable length long
values over 2,000,000,000 bytes in length.
.PP
Since values of that size can't usually be held in memory, and because
databases can't usually know in advance the length of the longest long
that will be returned from a \f(CW\*(C`SELECT\*(C'\fR statement (unlike other data
types), some special handling is required.
.PP
In this situation, the value of the \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`{LongReadLen}\*(C'\fR attribute is used
to determine how much buffer space to allocate when fetching such
fields. The \f(CW\*(C`$h\-\*(C'\fR>\f(CW\*(C`{LongTruncOk}\*(C'\fR attribute is used to determine how to
behave if a fetched value can't fit into the buffer.
.PP
When trying to insert long or binary values, placeholders should be used
since there are often limits on the maximum size of an \f(CW\*(C`INSERT\*(C'\fR
statement and the \*(L"quote\*(R" method generally can't cope with binary
data. See \*(L"Placeholders and Bind Values\*(R".
.Sh "Simple Examples"
.IX Subsection "Simple Examples"
Here's a complete example program to select and fetch some data:
.PP
.Vb 2
\& my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password)
\& or die "Can't connect to $data_source: $DBI::errstr";
.Ve
.PP
.Vb 4
\& my $sth = $dbh->prepare( q{
\& SELECT name, phone
\& FROM mytelbook
\& }) or die "Can't prepare statement: $DBI::errstr";
.Ve
.PP
.Vb 2
\& my $rc = $sth->execute
\& or die "Can't execute statement: $DBI::errstr";
.Ve
.PP
.Vb 2
\& print "Query will return $sth->{NUM_OF_FIELDS} fields.\en\en";
\& print "Field names: @{ $sth->{NAME} }\en";
.Ve
.PP
.Vb 5
\& while (($name, $phone) = $sth->fetchrow_array) {
\& print "$name: $phone\en";
\& }
\& # check for problems which may have terminated the fetch early
\& die $sth->errstr if $sth->err;
.Ve
.PP
.Vb 1
\& $dbh->disconnect;
.Ve
.PP
Here's a complete example program to insert some data from a file.
(This example uses \f(CW\*(C`RaiseError\*(C'\fR to avoid needing to check each call).
.PP
.Vb 3
\& my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, {
\& RaiseError => 1, AutoCommit => 0
\& });
.Ve
.PP
.Vb 3
\& my $sth = $dbh->prepare( q{
\& INSERT INTO table (name, phone) VALUES (?, ?)
\& });
.Ve
.PP
.Vb 7
\& open FH, "<phone.csv" or die "Unable to open phone.csv: $!";
\& while (<FH>) {
\& chomp;
\& my ($name, $phone) = split /,/;
\& $sth->execute($name, $phone);
\& }
\& close FH;
.Ve
.PP
.Vb 2
\& $dbh->commit;
\& $dbh->disconnect;
.Ve
.PP
Here's how to convert fetched NULLs (undefined values) into empty strings:
.PP
.Vb 5
\& while($row = $sth->fetchrow_arrayref) {
\& # this is a fast and simple way to deal with nulls:
\& foreach (@$row) { $_ = '' unless defined }
\& print "@$row\en";
\& }
.Ve
.PP
The \f(CW\*(C`q{...}\*(C'\fR style quoting used in these examples avoids clashing with
quotes that may be used in the \s-1SQL\s0 statement. Use the double-quote like
\&\f(CW\*(C`qq{...}\*(C'\fR operator if you want to interpolate variables into the string.
See \*(L"Quote and Quote-like Operators\*(R" in perlop for more details.
.Sh "Threads and Thread Safety"
.IX Subsection "Threads and Thread Safety"
Perl versions 5.004_50 and later include optional experimental support
for multiple threads on many platforms. If the \s-1DBI\s0 is built using a
Perl that has threads enabled then it will use a per-driver mutex to
ensure that only one thread is with a driver at any one time.
Please note that support for threads in Perl is still experimental and
is known to have some significant problems. It's use is not recommended.
.Sh "Signal Handling and Canceling Operations"
.IX Subsection "Signal Handling and Canceling Operations"
The first thing to say is that signal handling in Perl is currently
\&\fInot\fR safe. There is always a small risk of Perl crashing and/or
core dumping when, or after, handling a signal. (The risk was reduced
with 5.004_04 but is still present.)
.PP
The two most common uses of signals in relation to the \s-1DBI\s0 are for
canceling operations when the user types Ctrl-C (interrupt), and for
implementing a timeout using \f(CW\*(C`alarm()\*(C'\fR and \f(CW$SIG{ALRM}\fR.
.PP
To assist in implementing these operations, the \s-1DBI\s0 provides a \f(CW\*(C`cancel\*(C'\fR
method for statement handles. The \f(CW\*(C`cancel\*(C'\fR method should abort the current
operation and is designed to be called from a signal handler.
.PP
However, it must be stressed that: a) few drivers implement this at
the moment (the \s-1DBI\s0 provides a default method that just returns \f(CW\*(C`undef\*(C'\fR);
and b) even if implemented, there is still a possibility that the statement
handle, and possibly the parent database handle, will not be usable
afterwards.
.PP
If \f(CW\*(C`cancel\*(C'\fR returns true, then it has successfully
invoked the database engine's own cancel function. If it returns false,
then \f(CW\*(C`cancel\*(C'\fR failed. If it returns \f(CW\*(C`undef\*(C'\fR, then the database
engine does not have cancel implemented.
.SH "DEBUGGING"
.IX Header "DEBUGGING"
In addition to the \*(L"trace\*(R" method, you can enable the same trace
information by setting the \f(CW\*(C`DBI_TRACE\*(C'\fR environment variable before
starting Perl.
.PP
On Unix-like systems using a Bourne-like shell, you can do this easily
on the command line:
.PP
.Vb 1
\& DBI_TRACE=2 perl your_test_script.pl
.Ve
.PP
If \f(CW\*(C`DBI_TRACE\*(C'\fR is set to a non-numeric value, then it is assumed to
be a file name and the trace level will be set to 2 with all trace
output appended to that file. If the name begins with a number
followed by an equal sign (\f(CW\*(C`=\*(C'\fR), then the number and the equal sign are
stripped off from the name, and the number is used to set the trace
level. For example:
.PP
.Vb 1
\& DBI_TRACE=1=dbitrace.log perl your_test_script.pl
.Ve
.PP
See also the \*(L"trace\*(R" method.
.PP
It can sometimes be handy to compare trace files from two different
runs of the same script. However using a tool like \f(CW\*(C`diff\*(C'\fR doesn't work
well because the trace file is full of object addresses that may
differ each run. Here's a handy little command to strip those out:
.PP
.Vb 1
\& perl -pe 's/\eb0x[\eda-f]{6,}/0xNNNN/gi; s/\eb[\eda-f]{6,}/<long number>/gi'
.Ve
.SH "WARNING AND ERROR MESSAGES"
.IX Header "WARNING AND ERROR MESSAGES"
.Sh "Fatal Errors"
.IX Subsection "Fatal Errors"
.ie n .IP "Can't call method ""prepare"" without a package or object reference" 4
.el .IP "Can't call method ``prepare'' without a package or object reference" 4
.IX Item "Can't call method prepare without a package or object reference"
The \f(CW$dbh\fR handle you're using to call \f(CW\*(C`prepare\*(C'\fR is probably undefined because
the preceding \f(CW\*(C`connect\*(C'\fR failed. You should always check the return status of
\&\s-1DBI\s0 methods, or use the \*(L"RaiseError\*(R" attribute.
.ie n .IP "Can't call method ""execute"" without a package or object reference" 4
.el .IP "Can't call method ``execute'' without a package or object reference" 4
.IX Item "Can't call method execute without a package or object reference"
The \f(CW$sth\fR handle you're using to call \f(CW\*(C`execute\*(C'\fR is probably undefined because
the preceeding \f(CW\*(C`prepare\*(C'\fR failed. You should always check the return status of
\&\s-1DBI\s0 methods, or use the \*(L"RaiseError\*(R" attribute.
.IP "\s-1DBI/DBD\s0 internal version mismatch" 4
.IX Item "DBI/DBD internal version mismatch"
The \s-1DBD\s0 driver module was built with a different version of \s-1DBI\s0 than
the one currently being used. You should rebuild the \s-1DBD\s0 module under
the current version of \s-1DBI\s0.
.Sp
(Some rare platforms require \*(L"static linking\*(R". On those platforms, there
may be an old \s-1DBI\s0 or \s-1DBD\s0 driver version actually embedded in the Perl
executable being used.)
.IP "\s-1DBD\s0 driver has not implemented the AutoCommit attribute" 4
.IX Item "DBD driver has not implemented the AutoCommit attribute"
The \s-1DBD\s0 driver implementation is incomplete. Consult the author.
.ie n .IP "Can't [sg]et %s\->{%s}: unrecognised attribute" 4
.el .IP "Can't [sg]et \f(CW%s\fR\->{%s}: unrecognised attribute" 4
.IX Item "Can't [sg]et %s->{%s}: unrecognised attribute"
You attempted to set or get an unknown attribute of a handle. Make
sure you have spelled the attribute name correctly; case is significant
(e.g., \*(L"Autocommit\*(R" is not the same as \*(L"AutoCommit\*(R").
.Sh "Warnings"
.IX Subsection "Warnings"
.IP "Database handle destroyed without explicit disconnect" 4
.IX Item "Database handle destroyed without explicit disconnect"
A \f(CW$dbh\fR handle went out of scope or the program ended before the handle
was disconnected from the database. You should always explicitly call
\&\f(CW\*(C`disconnect\*(C'\fR when you are finished using a database handle. If using
transactions then you should also explicitly call \f(CW\*(C`commit\*(C'\fR or \f(CW\*(C`rollback\*(C'\fR
before \f(CW\*(C`disconnect\*(C'\fR.
.ie n .IP "\s-1DBI\s0 Handle cleared whilst still holding %d cached kids!" 4
.el .IP "\s-1DBI\s0 Handle cleared whilst still holding \f(CW%d\fR cached kids!" 4
.IX Item "DBI Handle cleared whilst still holding %d cached kids!"
Most probably due to a \s-1DBI\s0 bug. Possibly a \s-1DBD\s0 driver bug. Please report it.
.IP "\s-1DBI\s0 Handle cleared whilst still active!" 4
.IX Item "DBI Handle cleared whilst still active!"
Most probably due to a \s-1DBI\s0 bug. Possibly a \s-1DBD\s0 driver bug. Please report it.
.IP "\s-1DBI\s0 Handle has uncleared implementors data" 4
.IX Item "DBI Handle has uncleared implementors data"
Most probably a \s-1DBD\s0 driver bug. Please report it.
.ie n .IP "\s-1DBI\s0 Handle has %d uncleared child handles" 4
.el .IP "\s-1DBI\s0 Handle has \f(CW%d\fR uncleared child handles" 4
.IX Item "DBI Handle has %d uncleared child handles"
Most probably due to a \s-1DBI\s0 bug. Possibly a \s-1DBD\s0 driver bug. Please report it.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
.Sh "Driver and Database Documentation"
.IX Subsection "Driver and Database Documentation"
Refer to the documentation for the \s-1DBD\s0 driver that you are using.
.PP
Refer to the \s-1SQL\s0 Language Reference Manual for the database engine that you are using.
.Sh "Books and Journals"
.IX Subsection "Books and Journals"
.Vb 1
\& Programming the Perl DBI, by Alligator Descartes and Tim Bunce.
.Ve
.PP
.Vb 1
\& Programming Perl 2nd Ed. by Larry Wall, Tom Christiansen & Randal Schwartz.
.Ve
.PP
.Vb 1
\& Learning Perl by Randal Schwartz.
.Ve
.PP
.Vb 1
\& Dr Dobb's Journal, November 1996.
.Ve
.PP
.Vb 1
\& The Perl Journal, April 1997.
.Ve
.Sh "Manual Pages"
.IX Subsection "Manual Pages"
\&\fIperl\fR\|(1), \fIperlmod\fR\|(1), \fIperlbook\fR\|(1)
.Sh "Mailing List"
.IX Subsection "Mailing List"
The \fIdbi-users\fR mailing list is the primary means of communication among
users of the \s-1DBI\s0 and its related modules. For details send email to:
.PP
.Vb 1
\& dbi-users-help@perl.org
.Ve
.PP
There are typically between 700 and 900 messages per month. You have
to subscribe in order to be able to post. However you can opt for a
\&'post\-only' subscription.
.PP
Mailing list archives are held at:
.PP
.Vb 6
\& http://www.xray.mpe.mpg.de/mailing-lists/dbi/
\& http://groups.yahoo.com/group/dbi-users
\& http://www.bitmechanic.com/mail-archives/dbi-users/
\& http://marc.theaimsgroup.com/?l=perl-dbi&r=1&w=2
\& http://www.mail-archive.com/dbi-users%40perl.org/
\& http://www.mail-archive.com/dbi-users%40perl.org/
.Ve
.Sh "Assorted Related \s-1WWW\s0 Links"
.IX Subsection "Assorted Related WWW Links"
The \s-1DBI\s0 \*(L"Home Page\*(R":
.PP
.Vb 1
\& http://dbi.perl.org/
.Ve
.PP
Other \s-1DBI\s0 related links:
.PP
.Vb 5
\& http://tegan.deltanet.com/~phlip/DBUIdoc.html
\& http://dc.pm.org/perl_db.html
\& http://wdvl.com/Authoring/DB/Intro/toc.html
\& http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html
\& http://bumppo.net/lists/macperl/1999/06/msg00197.html
.Ve
.PP
Other database related links:
.PP
.Vb 2
\& http://www.jcc.com/sql_stnd.html
\& http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
.Ve
.PP
Commercial and Data Warehouse Links
.PP
.Vb 6
\& http://www.dwinfocenter.org
\& http://www.datawarehouse.com
\& http://www.datamining.org
\& http://www.olapcouncil.org
\& http://www.idwa.org
\& http://www.knowledgecenters.org/dwcenter.asp
.Ve
.PP
Recommended Perl Programming Links
.PP
.Vb 1
\& http://language.perl.com/style/
.Ve
.Sh "\s-1FAQ\s0"
.IX Subsection "FAQ"
Please also read the \s-1DBI\s0 \s-1FAQ\s0 which is installed as a \s-1DBI::FAQ\s0 module.
You can use \fIperldoc\fR to read it by executing the \f(CW\*(C`perldoc DBI::FAQ\*(C'\fR command.
.SH "AUTHORS"
.IX Header "AUTHORS"
\&\s-1DBI\s0 by Tim Bunce. This pod text by Tim Bunce, J. Douglas Dunlop,
Jonathan Leffler and others. Perl by Larry Wall and the
\&\f(CW\*(C`perl5\-porters\*(C'\fR.
.SH "COPYRIGHT"
.IX Header "COPYRIGHT"
The \s-1DBI\s0 module is Copyright (c) 1994\-2000 Tim Bunce. England.
All rights reserved.
.PP
You may distribute under the terms of either the \s-1GNU\s0 General Public
License or the Artistic License, as specified in the Perl \s-1README\s0 file.
.SH "ACKNOWLEDGEMENTS"
.IX Header "ACKNOWLEDGEMENTS"
I would like to acknowledge the valuable contributions of the many
people I have worked with on the \s-1DBI\s0 project, especially in the early
years (1992\-1994). In no particular order: Kevin Stock, Buzz Moschetti,
Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler,
Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander,
Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson,
Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen,
Steve Baumgarten, Randal Schwartz, and a whole lot more.
.PP
Then, of course, there are the poor souls who have struggled through
untold and undocumented obstacles to actually implement \s-1DBI\s0 drivers.
Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan
Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo,
Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve
Williams, Thomas Lowery, and Phlip Plumlee. Without them, the \s-1DBI\s0 would
not be the practical reality it is today. I'm also especially grateful
to Alligator Descartes for starting work on the \*(L"Programming the Perl
\&\s-1DBI\s0\*(R" book and letting me jump on board.
.SH "TRANSLATIONS"
.IX Header "TRANSLATIONS"
A German translation of this manual (possibly slightly out of date) is
available, thanks to O'Reilly, at:
.PP
.Vb 1
\& http://www.oreilly.de/catalog/perldbiger/
.Ve
.PP
Some other translations:
.PP
.Vb 2
\& http://cronopio.net/perl/ - Spanish
\& http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese
.Ve
.SH "SUPPORT / WARRANTY"
.IX Header "SUPPORT / WARRANTY"
The \s-1DBI\s0 is free software. \s-1IT\s0 \s-1COMES\s0 \s-1WITHOUT\s0 \s-1WARRANTY\s0 \s-1OF\s0 \s-1ANY\s0 \s-1KIND\s0.
.PP
Commercial support for Perl and the \s-1DBI\s0, DBD::Oracle and
Oraperl modules can be arranged via The Perl Clinic.
For more details visit:
.PP
.Vb 1
\& http://www.perlclinic.com
.Ve
.SH "TRAINING"
.IX Header "TRAINING"
References to \s-1DBI\s0 related training resources. No recommendation implied.
.PP
.Vb 2
\& http://www.treepax.co.uk/
\& http://www.keller.com/dbweb/
.Ve
.SH "FREQUENTLY ASKED QUESTIONS"
.IX Header "FREQUENTLY ASKED QUESTIONS"
See the \s-1DBI\s0 \s-1FAQ\s0 for a more comprehensive list of FAQs. Use the
\&\f(CW\*(C`perldoc DBI::FAQ\*(C'\fR command to read it.
.Sh "How fast is the \s-1DBI\s0?"
.IX Subsection "How fast is the DBI?"
To measure the speed of the \s-1DBI\s0 and DBD::Oracle code, I modified
DBD::Oracle so you can set an attribute that will cause the
same row to be fetched from the row cache over and over again (without
involving Oracle code but exercising *all* the \s-1DBI\s0 and DBD::Oracle code
in the code path for a fetch).
.PP
The results (on my lightly loaded old Sparc 10) fetching 50000 rows using:
.PP
.Vb 1
\& 1 while $csr->fetch;
.Ve
.PP
were:
one field: 5300 fetches per cpu second (approx)
ten fields: 4000 fetches per cpu second (approx)
.PP
Obviously results will vary between platforms (newer faster platforms
can reach around 50000 fetches per second), but it does give a feel for
the maximum performance: fast. By way of comparison, using the code:
.PP
.Vb 1
\& 1 while @row = $csr->fetchrow_array;
.Ve
.PP
(\f(CW\*(C`fetchrow_array\*(C'\fR is roughly the same as \f(CW\*(C`ora_fetch\*(C'\fR) gives:
.PP
.Vb 2
\& one field: 3100 fetches per cpu second (approx)
\& ten fields: 1000 fetches per cpu second (approx)
.Ve
.PP
Notice the slowdown and the more dramatic impact of extra fields.
(The fields were all one char long. The impact would be even bigger for
longer strings.)
.PP
Changing that slightly to represent actually doing something in Perl
with the fetched data:
.PP
.Vb 3
\& while(@row = $csr->fetchrow_array) {
\& $hash{++$i} = [ @row ];
\& }
.Ve
.PP
gives: ten fields: 500 fetches per cpu second (approx)
.PP
That simple addition has *halved* the performance.
.PP
I therefore conclude that \s-1DBI\s0 and DBD::Oracle overheads are small
compared with Perl language overheads (and probably database overheads).
.PP
So, if you think the \s-1DBI\s0 or your driver is slow, try replacing your
fetch loop with just:
.PP
.Vb 1
\& 1 while $csr->fetch;
.Ve
.PP
and time that. If that helps then point the finger at your own code. If
that doesn't help much then point the finger at the database, the
platform, the network etc. But think carefully before pointing it at
the \s-1DBI\s0 or your driver.
.PP
(Having said all that, if anyone can show me how to make the \s-1DBI\s0 or
drivers even more efficient, I'm all ears.)
.Sh "Why doesn't my \s-1CGI\s0 script work right?"
.IX Subsection "Why doesn't my CGI script work right?"
Read the information in the references below. Please do \fInot\fR post
\&\s-1CGI\s0 related questions to the \fIdbi-users\fR mailing list (or to me).
.PP
.Vb 5
\& http://www.perl.com/cgi-bin/pace/pub/doc/FAQs/cgi/perl-cgi-faq.html
\& http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
\& http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
\& http://www.boutell.com/faq/
\& http://www.perl.com/perl/faq/
.Ve
.PP
General problems and good ideas:
.PP
.Vb 2
\& Use the CGI::ErrorWrap module.
\& Remember that many env vars won't be set for CGI scripts.
.Ve
.Sh "How can I maintain a \s-1WWW\s0 connection to a database?"
.IX Subsection "How can I maintain a WWW connection to a database?"
For information on the Apache httpd server and the \f(CW\*(C`mod_perl\*(C'\fR module see
.PP
.Vb 1
\& http://perl.apache.org/
.Ve
.Sh "What about \s-1ODBC\s0?"
.IX Subsection "What about ODBC?"
A \s-1DBD::ODBC\s0 module is available.
.Sh "Does the \s-1DBI\s0 have a year 2000 problem?"
.IX Subsection "Does the DBI have a year 2000 problem?"
No. The \s-1DBI\s0 has no knowledge or understanding of dates at all.
.PP
Individual drivers (DBD::*) may have some date handling code but are
unlikely to have year 2000 related problems within their code. However,
your application code which \fIuses\fR the \s-1DBI\s0 and \s-1DBD\s0 drivers may have
year 2000 related problems if it has not been designed and written well.
.PP
See also the \*(L"Does Perl have a year 2000 problem?\*(R" section of the Perl \s-1FAQ:\s0
.PP
.Vb 1
\& http://www.perl.com/CPAN/doc/FAQs/FAQ/PerlFAQ.html
.Ve
.SH "OTHER RELATED WORK AND PERL MODULES"
.IX Header "OTHER RELATED WORK AND PERL MODULES"
.IP "Apache::DBI by E.Mergl@bawue.de" 4
.IX Item "Apache::DBI by E.Mergl@bawue.de"
To be used with the Apache daemon together with an embedded Perl
interpreter like \f(CW\*(C`mod_perl\*(C'\fR. Establishes a database connection which
remains open for the lifetime of the \s-1HTTP\s0 daemon. This way the \s-1CGI\s0
connect and disconnect for every database access becomes superfluous.
.IP "\s-1JDBC\s0 Server by Stuart 'Zen' Bishop zen@bf.rmit.edu.au" 4
.IX Item "JDBC Server by Stuart 'Zen' Bishop zen@bf.rmit.edu.au"
The server is written in Perl. The client classes that talk to it are
of course in Java. Thus, a Java applet or application will be able to
comunicate via the \s-1JDBC\s0 \s-1API\s0 with any database that has a \s-1DBI\s0 driver installed.
The \s-1URL\s0 used is in the form \f(CW\*(C`jdbc:dbi://host.domain.etc:999/Driver/DBName\*(C'\fR.
It seems to be very similar to some commercial products, such as jdbcKona.
.IP "Remote Proxy \s-1DBD\s0 support" 4
.IX Item "Remote Proxy DBD support"
As of \s-1DBI\s0 1.02, a complete implementation of a DBD::Proxy driver and the
DBI::ProxyServer are part of the \s-1DBI\s0 distribution.
.IP "\s-1SQL\s0 Parser" 4
.IX Item "SQL Parser"
.Vb 2
\& Hugo van der Sanden <hv@crypt.compulink.co.uk>
\& Stephen Zander <stephen.zander@mckesson.com>
.Ve
.Sp
Based on the O'Reilly lex/yacc book examples and \f(CW\*(C`byacc\*(C'\fR.
.Sp
See also the SQL::Statement module, a very simple \s-1SQL\s0 parser and engine,
base of the \s-1DBD::CSV\s0 driver.