1DBI(3) User Contributed Perl Documentation DBI(3)
2
3
4
6 DBI - Database independent interface for Perl
7
9 use DBI;
10
11 @driver_names = DBI->available_drivers;
12 %drivers = DBI->installed_drivers;
13 @data_sources = DBI->data_sources($driver_name, \%attr);
14
15 $dbh = DBI->connect($data_source, $username, $auth, \%attr);
16
17 $rv = $dbh->do($statement);
18 $rv = $dbh->do($statement, \%attr);
19 $rv = $dbh->do($statement, \%attr, @bind_values);
20
21 $ary_ref = $dbh->selectall_arrayref($statement);
22 $hash_ref = $dbh->selectall_hashref($statement, $key_field);
23
24 $ary_ref = $dbh->selectcol_arrayref($statement);
25 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
26
27 @row_ary = $dbh->selectrow_array($statement);
28 $ary_ref = $dbh->selectrow_arrayref($statement);
29 $hash_ref = $dbh->selectrow_hashref($statement);
30
31 $sth = $dbh->prepare($statement);
32 $sth = $dbh->prepare_cached($statement);
33
34 $rc = $sth->bind_param($p_num, $bind_value);
35 $rc = $sth->bind_param($p_num, $bind_value, $bind_type);
36 $rc = $sth->bind_param($p_num, $bind_value, \%attr);
37
38 $rv = $sth->execute;
39 $rv = $sth->execute(@bind_values);
40 $rv = $sth->execute_array(\%attr, ...);
41
42 $rc = $sth->bind_col($col_num, \$col_variable);
43 $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
44
45 @row_ary = $sth->fetchrow_array;
46 $ary_ref = $sth->fetchrow_arrayref;
47 $hash_ref = $sth->fetchrow_hashref;
48
49 $ary_ref = $sth->fetchall_arrayref;
50 $ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
51
52 $hash_ref = $sth->fetchall_hashref( $key_field );
53
54 $rv = $sth->rows;
55
56 $rc = $dbh->begin_work;
57 $rc = $dbh->commit;
58 $rc = $dbh->rollback;
59
60 $quoted_string = $dbh->quote($string);
61
62 $rc = $h->err;
63 $str = $h->errstr;
64 $rv = $h->state;
65
66 $rc = $dbh->disconnect;
67
68 The synopsis above only lists the major methods and parameters.
69
70 GETTING HELP
71 If you have questions about DBI, or DBD driver modules, you can get
72 help from the dbi-users@perl.org mailing list. You don't have to
73 subscribe to the list in order to post, though I'd recommend it. You
74 can get help on subscribing and using the list by emailing
75 dbi-users-help@perl.org.
76
77 I don't recommend the DBI cpanforum (at
78 http://www.cpanforum.com/dist/DBI) because relatively few people read
79 it compared with dbi-users@perl.org.
80
81 To help you make the best use of the dbi-users mailing list, and any
82 other lists or forums you may use, I strongly recommend that you read
83 "How To Ask Questions The Smart Way" by Eric Raymond:
84 <http://www.catb.org/~esr/faqs/smart-questions.html>.
85
86 If you think you've found a bug then please also read "How to Report
87 Bugs Effectively" by Simon Tatham:
88 <http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>.
89
90 The DBI home page at <http://dbi.perl.org/> and the DBI FAQ at
91 <http://faq.dbi-support.com/> are always worth a visit. They include
92 links to other resources.
93
94 Before asking any questions, reread this document, consult the archives
95 and read the DBI FAQ. The archives are listed at the end of this
96 document and on the DBI home page.
97
98 This document often uses terms like references, objects, methods. If
99 you're not familiar with those terms then it would be a good idea to
100 read at least the following perl manuals first: perlreftut, perldsc,
101 perllol, and perlboot.
102
103 Please note that Tim Bunce does not maintain the mailing lists or the
104 web page (generous volunteers do that). So please don't send mail
105 directly to him; he just doesn't have the time to answer questions
106 personally. The dbi-users mailing list has lots of experienced people
107 who should be able to help you if you need it. If you do email Tim he's
108 very likely to just forward it to the mailing list.
109
110 NOTES
111 This is the DBI specification that corresponds to the DBI version 1.609
112 ($Revision: 12812 $).
113
114 The DBI is evolving at a steady pace, so it's good to check that you
115 have the latest copy.
116
117 The significant user-visible changes in each release are documented in
118 the DBI::Changes module so you can read them by executing "perldoc
119 DBI::Changes".
120
121 Some DBI changes require changes in the drivers, but the drivers can
122 take some time to catch up. Newer versions of the DBI have added
123 features that may not yet be supported by the drivers you use. Talk to
124 the authors of your drivers if you need a new feature that's not yet
125 supported.
126
127 Features added after DBI 1.21 (February 2002) are marked in the text
128 with the version number of the DBI release they first appeared in.
129
130 Extensions to the DBI API often use the "DBIx::*" namespace. See
131 "Naming Conventions and Name Space". DBI extension modules can be found
132 at <http://search.cpan.org/search?mode=module&query=DBIx>. And all
133 modules related to the DBI can be found at
134 <http://search.cpan.org/search?query=DBI&mode=all>.
135
137 The DBI is a database access module for the Perl programming language.
138 It defines a set of methods, variables, and conventions that provide a
139 consistent database interface, independent of the actual database being
140 used.
141
142 It is important to remember that the DBI is just an interface. The DBI
143 is a layer of "glue" between an application and one or more database
144 driver modules. It is the driver modules which do most of the real
145 work. The DBI provides a standard interface and framework for the
146 drivers to operate within.
147
148 Architecture of a DBI Application
149 |<- Scope of DBI ->|
150 .-. .--------------. .-------------.
151 .-------. | |---| XYZ Driver |---| XYZ Engine |
152 | Perl | | | `--------------' `-------------'
153 | script| |A| |D| .--------------. .-------------.
154 | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
155 | DBI | |I| |I| `--------------' `-------------'
156 | API | | |...
157 |methods| | |... Other drivers
158 `-------' | |...
159 `-'
160
161 The API, or Application Programming Interface, defines the call
162 interface and variables for Perl scripts to use. The API is implemented
163 by the Perl DBI extension.
164
165 The DBI "dispatches" the method calls to the appropriate driver for
166 actual execution. The DBI is also responsible for the dynamic loading
167 of drivers, error checking and handling, providing default
168 implementations for methods, and many other non-database specific
169 duties.
170
171 Each driver contains implementations of the DBI methods using the
172 private interface functions of the corresponding database engine. Only
173 authors of sophisticated/multi-database applications or generic library
174 functions need be concerned with drivers.
175
176 Notation and Conventions
177 The following conventions are used in this document:
178
179 $dbh Database handle object
180 $sth Statement handle object
181 $drh Driver handle object (rarely seen or used in applications)
182 $h Any of the handle types above ($dbh, $sth, or $drh)
183 $rc General Return Code (boolean: true=ok, false=error)
184 $rv General Return Value (typically an integer)
185 @ary List of values returned from the database, typically a row of data
186 $rows Number of rows processed (if available, else -1)
187 $fh A filehandle
188 undef NULL values are represented by undefined values in Perl
189 \%attr Reference to a hash of attribute values passed to methods
190
191 Note that Perl will automatically destroy database and statement handle
192 objects if all references to them are deleted.
193
194 Outline Usage
195 To use DBI, first you need to load the DBI module:
196
197 use DBI;
198 use strict;
199
200 (The "use strict;" isn't required but is strongly recommended.)
201
202 Then you need to "connect" to your data source and get a handle for
203 that connection:
204
205 $dbh = DBI->connect($dsn, $user, $password,
206 { RaiseError => 1, AutoCommit => 0 });
207
208 Since connecting can be expensive, you generally just connect at the
209 start of your program and disconnect at the end.
210
211 Explicitly defining the required "AutoCommit" behaviour is strongly
212 recommended and may become mandatory in a later version. This
213 determines whether changes are automatically committed to the database
214 when executed, or need to be explicitly committed later.
215
216 The DBI allows an application to "prepare" statements for later
217 execution. A prepared statement is identified by a statement handle
218 held in a Perl variable. We'll call the Perl variable $sth in our
219 examples.
220
221 The typical method call sequence for a "SELECT" statement is:
222
223 prepare,
224 execute, fetch, fetch, ...
225 execute, fetch, fetch, ...
226 execute, fetch, fetch, ...
227
228 for example:
229
230 $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
231
232 $sth->execute( $baz );
233
234 while ( @row = $sth->fetchrow_array ) {
235 print "@row\n";
236 }
237
238 The typical method call sequence for a non-"SELECT" statement is:
239
240 prepare,
241 execute,
242 execute,
243 execute.
244
245 for example:
246
247 $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
248
249 while(<CSV>) {
250 chomp;
251 my ($foo,$bar,$baz) = split /,/;
252 $sth->execute( $foo, $bar, $baz );
253 }
254
255 The "do()" method can be used for non repeated non-"SELECT" statement
256 (or with drivers that don't support placeholders):
257
258 $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
259
260 To commit your changes to the database (when "AutoCommit" is off):
261
262 $dbh->commit; # or call $dbh->rollback; to undo changes
263
264 Finally, when you have finished working with the data source, you
265 should "disconnect" from it:
266
267 $dbh->disconnect;
268
269 General Interface Rules & Caveats
270 The DBI does not have a concept of a "current session". Every session
271 has a handle object (i.e., a $dbh) returned from the "connect" method.
272 That handle object is used to invoke database related methods.
273
274 Most data is returned to the Perl script as strings. (Null values are
275 returned as "undef".) This allows arbitrary precision numeric data to
276 be handled without loss of accuracy. Beware that Perl may not preserve
277 the same accuracy when the string is used as a number.
278
279 Dates and times are returned as character strings in the current
280 default format of the corresponding database engine. Time zone effects
281 are database/driver dependent.
282
283 Perl supports binary data in Perl strings, and the DBI will pass binary
284 data to and from the driver without change. It is up to the driver
285 implementors to decide how they wish to handle such binary data.
286
287 Perl supports two kinds of strings: unicode (utf8 internally) and non-
288 unicode (defaults to iso-8859-1 if forced to assume an encoding).
289 Drivers should accept both kinds of strings and, if required, convert
290 them to the character set of the database being used. Similarly, when
291 fetching from the database character data that isn't iso-8859-1 the
292 driver should convert it into utf8.
293
294 Multiple SQL statements may not be combined in a single statement
295 handle ($sth), although some databases and drivers do support this
296 (notably Sybase and SQL Server).
297
298 Non-sequential record reads are not supported in this version of the
299 DBI. In other words, records can only be fetched in the order that the
300 database returned them, and once fetched they are forgotten.
301
302 Positioned updates and deletes are not directly supported by the DBI.
303 See the description of the "CursorName" attribute for an alternative.
304
305 Individual driver implementors are free to provide any private
306 functions and/or handle attributes that they feel are useful. Private
307 driver functions can be invoked using the DBI "func()" method. Private
308 driver attributes are accessed just like standard attributes.
309
310 Many methods have an optional "\%attr" parameter which can be used to
311 pass information to the driver implementing the method. Except where
312 specifically documented, the "\%attr" parameter can only be used to
313 pass driver specific hints. In general, you can ignore "\%attr"
314 parameters or pass it as "undef".
315
316 Naming Conventions and Name Space
317 The DBI package and all packages below it ("DBI::*") are reserved for
318 use by the DBI. Extensions and related modules use the "DBIx::"
319 namespace (see <http://www.perl.com/CPAN/modules/by-module/DBIx/>).
320 Package names beginning with "DBD::" are reserved for use by DBI
321 database drivers. All environment variables used by the DBI or by
322 individual DBDs begin with ""DBI_"" or ""DBD_"".
323
324 The letter case used for attribute names is significant and plays an
325 important part in the portability of DBI scripts. The case of the
326 attribute name is used to signify who defined the meaning of that name
327 and its values.
328
329 Case of name Has a meaning defined by
330 ------------ ------------------------
331 UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable)
332 MixedCase DBI API (portable), underscores are not used.
333 lower_case Driver or database engine specific (non-portable)
334
335 It is of the utmost importance that Driver developers only use
336 lowercase attribute names when defining private attributes. Private
337 attribute names must be prefixed with the driver name or suitable
338 abbreviation (e.g., ""ora_"" for Oracle, ""ing_"" for Ingres, etc).
339
340 SQL - A Query Language
341 Most DBI drivers require applications to use a dialect of SQL
342 (Structured Query Language) to interact with the database engine. The
343 "Standards Reference Information" section provides links to useful
344 information about SQL.
345
346 The DBI itself does not mandate or require any particular language to
347 be used; it is language independent. In ODBC terms, the DBI is in
348 "pass-thru" mode, although individual drivers might not be. The only
349 requirement is that queries and other statements must be expressed as a
350 single string of characters passed as the first argument to the
351 "prepare" or "do" methods.
352
353 For an interesting diversion on the real history of RDBMS and SQL, from
354 the people who made it happen, see:
355
356 http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
357
358 Follow the "Full Contents" then "Intergalactic dataspeak" links for the
359 SQL history.
360
361 Placeholders and Bind Values
362 Some drivers support placeholders and bind values. Placeholders, also
363 called parameter markers, are used to indicate values in a database
364 statement that will be supplied later, before the prepared statement is
365 executed. For example, an application might use the following to
366 insert a row of data into the SALES table:
367
368 INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
369
370 or the following, to select the description for a product:
371
372 SELECT description FROM products WHERE product_code = ?
373
374 The "?" characters are the placeholders. The association of actual
375 values with placeholders is known as binding, and the values are
376 referred to as bind values. Note that the "?" is not enclosed in
377 quotation marks, even when the placeholder represents a string.
378
379 Some drivers also allow placeholders like ":"name and ":"N (e.g., ":1",
380 ":2", and so on) in addition to "?", but their use is not portable.
381
382 If the ":"N form of placeholder is supported by the driver you're
383 using, then you should be able to use either "bind_param" or "execute"
384 to bind values. Check your driver documentation.
385
386 With most drivers, placeholders can't be used for any element of a
387 statement that would prevent the database server from validating the
388 statement and creating a query execution plan for it. For example:
389
390 "SELECT name, age FROM ?" # wrong (will probably fail)
391 "SELECT name, ? FROM people" # wrong (but may not 'fail')
392
393 Also, placeholders can only represent single scalar values. For
394 example, the following statement won't work as expected for more than
395 one value:
396
397 "SELECT name, age FROM people WHERE name IN (?)" # wrong
398 "SELECT name, age FROM people WHERE name IN (?,?)" # two names
399
400 When using placeholders with the SQL "LIKE" qualifier, you must
401 remember that the placeholder substitutes for the whole string. So you
402 should use ""... LIKE ? ..."" and include any wildcard characters in
403 the value that you bind to the placeholder.
404
405 NULL Values
406
407 Undefined values, or "undef", are used to indicate NULL values. You
408 can insert and update columns with a NULL value as you would a non-NULL
409 value. These examples insert and update the column "age" with a NULL
410 value:
411
412 $sth = $dbh->prepare(qq{
413 INSERT INTO people (fullname, age) VALUES (?, ?)
414 });
415 $sth->execute("Joe Bloggs", undef);
416
417 $sth = $dbh->prepare(qq{
418 UPDATE people SET age = ? WHERE fullname = ?
419 });
420 $sth->execute(undef, "Joe Bloggs");
421
422 However, care must be taken when trying to use NULL values in a "WHERE"
423 clause. Consider:
424
425 SELECT fullname FROM people WHERE age = ?
426
427 Binding an "undef" (NULL) to the placeholder will not select rows which
428 have a NULL "age"! At least for database engines that conform to the
429 SQL standard. Refer to the SQL manual for your database engine or any
430 SQL book for the reasons for this. To explicitly select NULLs you have
431 to say ""WHERE age IS NULL"".
432
433 A common issue is to have a code fragment handle a value that could be
434 either "defined" or "undef" (non-NULL or NULL) at runtime. A simple
435 technique is to prepare the appropriate statement as needed, and
436 substitute the placeholder for non-NULL cases:
437
438 $sql_clause = defined $age? "age = ?" : "age IS NULL";
439 $sth = $dbh->prepare(qq{
440 SELECT fullname FROM people WHERE $sql_clause
441 });
442 $sth->execute(defined $age ? $age : ());
443
444 The following technique illustrates qualifying a "WHERE" clause with
445 several columns, whose associated values ("defined" or "undef") are in
446 a hash %h:
447
448 for my $col ("age", "phone", "email") {
449 if (defined $h{$col}) {
450 push @sql_qual, "$col = ?";
451 push @sql_bind, $h{$col};
452 }
453 else {
454 push @sql_qual, "$col IS NULL";
455 }
456 }
457 $sql_clause = join(" AND ", @sql_qual);
458 $sth = $dbh->prepare(qq{
459 SELECT fullname FROM people WHERE $sql_clause
460 });
461 $sth->execute(@sql_bind);
462
463 The techniques above call prepare for the SQL statement with each call
464 to execute. Because calls to prepare() can be expensive, performance
465 can suffer when an application iterates many times over statements like
466 the above.
467
468 A better solution is a single "WHERE" clause that supports both NULL
469 and non-NULL comparisons. Its SQL statement would need to be prepared
470 only once for all cases, thus improving performance. Several examples
471 of "WHERE" clauses that support this are presented below. But each
472 example lacks portability, robustness, or simplicity. Whether an
473 example is supported on your database engine depends on what SQL
474 extensions it provides, and where it supports the "?" placeholder in a
475 statement.
476
477 0) age = ?
478 1) NVL(age, xx) = NVL(?, xx)
479 2) ISNULL(age, xx) = ISNULL(?, xx)
480 3) DECODE(age, ?, 1, 0) = 1
481 4) age = ? OR (age IS NULL AND ? IS NULL)
482 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1)
483 6) age = ? OR (age IS NULL AND ? = 1)
484
485 Statements formed with the above "WHERE" clauses require execute
486 statements as follows. The arguments are required, whether their
487 values are "defined" or "undef".
488
489 0,1,2,3) $sth->execute($age);
490 4,5) $sth->execute($age, $age);
491 6) $sth->execute($age, defined($age) ? 0 : 1);
492
493 Example 0 should not work (as mentioned earlier), but may work on a few
494 database engines anyway (e.g. Sybase). Example 0 is part of examples
495 4, 5, and 6, so if example 0 works, these other examples may work, even
496 if the engine does not properly support the right hand side of the "OR"
497 expression.
498
499 Examples 1 and 2 are not robust: they require that you provide a valid
500 column value xx (e.g. '~') which is not present in any row. That means
501 you must have some notion of what data won't be stored in the column,
502 and expect clients to adhere to that.
503
504 Example 5 requires that you provide a stored procedure (SP_ISNULL in
505 this example) that acts as a function: it checks whether a value is
506 null, and returns 1 if it is, or 0 if not.
507
508 Example 6, the least simple, is probably the most portable, i.e., it
509 should work with with most, if not all, database engines.
510
511 Here is a table that indicates which examples above are known to work
512 on various database engines:
513
514 -----Examples------
515 0 1 2 3 4 5 6
516 - - - - - - -
517 Oracle 9 N Y N Y Y ? Y
518 Informix IDS 9 N N N Y N Y Y
519 MS SQL N N Y N Y ? Y
520 Sybase Y N N N N N Y
521 AnyData,DBM,CSV Y N N N Y Y* Y
522 SQLite 3.3 N N N N Y N N
523
524 * Works only because Example 0 works.
525
526 DBI provides a sample perl script that will test the examples above on
527 your database engine and tell you which ones work. It is located in
528 the ex/ subdirectory of the DBI source distribution, or here:
529 <http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl>
530 Please use the script to help us fill-in and maintain this table.
531
532 Performance
533
534 Without using placeholders, the insert statement shown previously would
535 have to contain the literal values to be inserted and would have to be
536 re-prepared and re-executed for each row. With placeholders, the insert
537 statement only needs to be prepared once. The bind values for each row
538 can be given to the "execute" method each time it's called. By avoiding
539 the need to re-prepare the statement for each row, the application
540 typically runs many times faster. Here's an example:
541
542 my $sth = $dbh->prepare(q{
543 INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
544 }) or die $dbh->errstr;
545 while (<>) {
546 chomp;
547 my ($product_code, $qty, $price) = split /,/;
548 $sth->execute($product_code, $qty, $price) or die $dbh->errstr;
549 }
550 $dbh->commit or die $dbh->errstr;
551
552 See "execute" and "bind_param" for more details.
553
554 The "q{...}" style quoting used in this example avoids clashing with
555 quotes that may be used in the SQL statement. Use the double-quote like
556 "qq{...}" operator if you want to interpolate variables into the
557 string. See "Quote and Quote-like Operators" in perlop for more
558 details.
559
560 See also the "bind_columns" method, which is used to associate Perl
561 variables with the output columns of a "SELECT" statement.
562
564 In this section, we cover the DBI class methods, utility functions, and
565 the dynamic attributes associated with generic DBI handles.
566
567 DBI Constants
568 Constants representing the values of the SQL standard types can be
569 imported individually by name, or all together by importing the special
570 ":sql_types" tag.
571
572 The names and values of all the defined SQL standard types can be
573 produced like this:
574
575 foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) {
576 printf "%s=%d\n", $_, &{"DBI::$_"};
577 }
578
579 These constants are defined by SQL/CLI, ODBC or both. "SQL_BIGINT" is
580 (currently) omitted, because SQL/CLI and ODBC provide conflicting
581 codes.
582
583 See the "type_info", "type_info_all", and "bind_param" methods for
584 possible uses.
585
586 Note that just because the DBI defines a named constant for a given
587 data type doesn't mean that drivers will support that data type.
588
589 DBI Class Methods
590 The following methods are provided by the DBI class:
591
592 "parse_dsn"
593
594 ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn)
595 or die "Can't parse DBI DSN '$dsn'";
596
597 Breaks apart a DBI Data Source Name (DSN) and returns the individual
598 parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns an
599 empty list.
600
601 $scheme is the first part of the DSN and is currently always 'dbi'.
602 $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER}, and
603 may be undefined. $attr_string is the contents of the optional
604 attribute string, which may be undefined. If $attr_string is not empty
605 then $attr_hash is a reference to a hash containing the parsed
606 attribute names and values. $driver_dsn is the last part of the DBI
607 DSN string. For example:
608
609 ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn)
610 = DBI->parse_dsn("DBI:MyDriver(RaiseError=>1):db=test;port=42");
611 $scheme = 'dbi';
612 $driver = 'MyDriver';
613 $attr_string = 'RaiseError=>1';
614 $attr_hash = { 'RaiseError' => '1' };
615 $driver_dsn = 'db=test;port=42';
616
617 The parse_dsn() method was added in DBI 1.43.
618
619 "connect"
620
621 $dbh = DBI->connect($data_source, $username, $password)
622 or die $DBI::errstr;
623 $dbh = DBI->connect($data_source, $username, $password, \%attr)
624 or die $DBI::errstr;
625
626 Establishes a database connection, or session, to the requested
627 $data_source. Returns a database handle object if the connection
628 succeeds. Use "$dbh->disconnect" to terminate the connection.
629
630 If the connect fails (see below), it returns "undef" and sets both
631 $DBI::err and $DBI::errstr. (It does not explicitly set $!.) You should
632 generally test the return status of "connect" and "print $DBI::errstr"
633 if it has failed.
634
635 Multiple simultaneous connections to multiple databases through
636 multiple drivers can be made via the DBI. Simply make one "connect"
637 call for each database and keep a copy of each returned database
638 handle.
639
640 The $data_source value must begin with ""dbi:"driver_name":"". The
641 driver_name specifies the driver that will be used to make the
642 connection. (Letter case is significant.)
643
644 As a convenience, if the $data_source parameter is undefined or empty,
645 the DBI will substitute the value of the environment variable
646 "DBI_DSN". If just the driver_name part is empty (i.e., the
647 $data_source prefix is ""dbi::""), the environment variable
648 "DBI_DRIVER" is used. If neither variable is set, then "connect" dies.
649
650 Examples of $data_source values are:
651
652 dbi:DriverName:database_name
653 dbi:DriverName:database_name@hostname:port
654 dbi:DriverName:database=database_name;host=hostname;port=port
655
656 There is no standard for the text following the driver name. Each
657 driver is free to use whatever syntax it wants. The only requirement
658 the DBI makes is that all the information is supplied in a single
659 string. You must consult the documentation for the drivers you are
660 using for a description of the syntax they require.
661
662 It is recommended that drivers support the ODBC style, shown in the
663 last example above. It is also recommended that that they support the
664 three common names '"host"', '"port"', and '"database"' (plus '"db"' as
665 an alias for "database"). This simplifies automatic construction of
666 basic DSNs: "dbi:$driver:database=$db;host=$host;port=$port". Drivers
667 should aim to 'do something reasonable' when given a DSN in this form,
668 but if any part is meaningless for that driver (such as 'port' for
669 Informix) it should generate an error if that part is not empty.
670
671 If the environment variable "DBI_AUTOPROXY" is defined (and the driver
672 in $data_source is not ""Proxy"") then the connect request will
673 automatically be changed to:
674
675 $ENV{DBI_AUTOPROXY};dsn=$data_source
676
677 "DBI_AUTOPROXY" is typically set as
678 ""dbi:Proxy:hostname=...;port=..."". If $ENV{DBI_AUTOPROXY} doesn't
679 begin with '"dbi:"' then "dbi:Proxy:" will be prepended to it first.
680 See the DBD::Proxy documentation for more details.
681
682 If $username or $password are undefined (rather than just empty), then
683 the DBI will substitute the values of the "DBI_USER" and "DBI_PASS"
684 environment variables, respectively. The DBI will warn if the
685 environment variables are not defined. However, the everyday use of
686 these environment variables is not recommended for security reasons.
687 The mechanism is primarily intended to simplify testing. See below for
688 alternative way to specify the username and password.
689
690 "DBI->connect" automatically installs the driver if it has not been
691 installed yet. Driver installation either returns a valid driver
692 handle, or it dies with an error message that includes the string
693 ""install_driver"" and the underlying problem. So "DBI->connect" will
694 die on a driver installation failure and will only return "undef" on a
695 connect failure, in which case $DBI::errstr will hold the error
696 message. Use "eval { ... }" if you need to catch the
697 ""install_driver"" error.
698
699 The $data_source argument (with the ""dbi:...:"" prefix removed) and
700 the $username and $password arguments are then passed to the driver for
701 processing. The DBI does not define any interpretation for the contents
702 of these fields. The driver is free to interpret the $data_source,
703 $username, and $password fields in any way, and supply whatever
704 defaults are appropriate for the engine being accessed. (Oracle, for
705 example, uses the ORACLE_SID and TWO_TASK environment variables if no
706 $data_source is specified.)
707
708 The "AutoCommit" and "PrintError" attributes for each connection
709 default to "on". (See "AutoCommit" and "PrintError" for more
710 information.) However, it is strongly recommended that you explicitly
711 define "AutoCommit" rather than rely on the default. The "PrintWarn"
712 attribute defaults to on if $^W is true, i.e., perl is running with
713 warnings enabled.
714
715 The "\%attr" parameter can be used to alter the default settings of
716 "PrintError", "RaiseError", "AutoCommit", and other attributes. For
717 example:
718
719 $dbh = DBI->connect($data_source, $user, $pass, {
720 PrintError => 0,
721 AutoCommit => 0
722 });
723
724 The username and password can also be specified using the attributes
725 "Username" and "Password", in which case they take precedence over the
726 $username and $password parameters.
727
728 You can also define connection attribute values within the $data_source
729 parameter. For example:
730
731 dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...
732
733 Individual attributes values specified in this way take precedence over
734 any conflicting values specified via the "\%attr" parameter to
735 "connect".
736
737 The "dbi_connect_method" attribute can be used to specify which driver
738 method should be called to establish the connection. The only useful
739 values are 'connect', 'connect_cached', or some specialized case like
740 'Apache::DBI::connect' (which is automatically the default when running
741 within Apache).
742
743 Where possible, each session ($dbh) is independent from the
744 transactions in other sessions. This is useful when you need to hold
745 cursors open across transactions--for example, if you use one session
746 for your long lifespan cursors (typically read-only) and another for
747 your short update transactions.
748
749 For compatibility with old DBI scripts, the driver can be specified by
750 passing its name as the fourth argument to "connect" (instead of
751 "\%attr"):
752
753 $dbh = DBI->connect($data_source, $user, $pass, $driver);
754
755 In this "old-style" form of "connect", the $data_source should not
756 start with ""dbi:driver_name:"". (If it does, the embedded driver_name
757 will be ignored). Also note that in this older form of "connect", the
758 "$dbh->{AutoCommit}" attribute is undefined, the "$dbh->{PrintError}"
759 attribute is off, and the old "DBI_DBNAME" environment variable is
760 checked if "DBI_DSN" is not defined. Beware that this "old-style"
761 "connect" will soon be withdrawn in a future version of DBI.
762
763 "connect_cached"
764
765 $dbh = DBI->connect_cached($data_source, $username, $password)
766 or die $DBI::errstr;
767 $dbh = DBI->connect_cached($data_source, $username, $password, \%attr)
768 or die $DBI::errstr;
769
770 "connect_cached" is like "connect", except that the database handle
771 returned is also stored in a hash associated with the given parameters.
772 If another call is made to "connect_cached" with the same parameter
773 values, then the corresponding cached $dbh will be returned if it is
774 still valid. The cached database handle is replaced with a new
775 connection if it has been disconnected or if the "ping" method fails.
776
777 That the behaviour of this method differs in several respects from the
778 behaviour of persistent connections implemented by Apache::DBI.
779 However, if Apache::DBI is loaded then "connect_cached" will use it.
780
781 Caching connections can be useful in some applications, but it can also
782 cause problems, such as too many connections, and so should be used
783 with care. In particular, avoid changing the attributes of a database
784 handle created via connect_cached() because it will affect other code
785 that may be using the same handle.
786
787 Where multiple separate parts of a program are using connect_cached()
788 to connect to the same database with the same (initial) attributes it
789 is a good idea to add a private attribute to the connect_cached() call
790 to effectively limit the scope of the caching. For example:
791
792 DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... });
793
794 Handles returned from that connect_cached() call will only be returned
795 by other connect_cached() call elsewhere in the code if those other
796 calls also pass in the same attribute values, including the private
797 one. (I've used "private_foo_cachekey" here as an example, you can use
798 any attribute name with a "private_" prefix.)
799
800 Taking that one step further, you can limit a particular
801 connect_cached() call to return handles unique to that one place in the
802 code by setting the private attribute to a unique value for that place:
803
804 DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... });
805
806 By using a private attribute you still get connection caching for the
807 individual calls to connect_cached() but, by making separate database
808 connections for separate parts of the code, the database handles are
809 isolated from any attribute changes made to other handles.
810
811 The cache can be accessed (and cleared) via the "CachedKids" attribute:
812
813 my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
814 %$CachedKids_hashref = () if $CachedKids_hashref;
815
816 "available_drivers"
817
818 @ary = DBI->available_drivers;
819 @ary = DBI->available_drivers($quiet);
820
821 Returns a list of all available drivers by searching for "DBD::*"
822 modules through the directories in @INC. By default, a warning is given
823 if some drivers are hidden by others of the same name in earlier
824 directories. Passing a true value for $quiet will inhibit the warning.
825
826 "installed_drivers"
827
828 %drivers = DBI->installed_drivers();
829
830 Returns a list of driver name and driver handle pairs for all drivers
831 'installed' (loaded) into the current process. The driver name does
832 not include the 'DBD::' prefix.
833
834 To get a list of all drivers available in your perl installation you
835 can use "available_drivers".
836
837 Added in DBI 1.49.
838
839 "installed_versions"
840
841 DBI->installed_versions;
842 @ary = DBI->installed_versions;
843 %hash = DBI->installed_versions;
844
845 Calls available_drivers() and attempts to load each of them in turn
846 using install_driver(). For each load that succeeds the driver name
847 and version number are added to a hash. When running under
848 DBI::PurePerl drivers which appear not be pure-perl are ignored.
849
850 When called in array context the list of successfully loaded drivers is
851 returned (without the 'DBD::' prefix).
852
853 When called in scalar context a reference to the hash is returned and
854 the hash will also contain other entries for the "DBI" version, "OS"
855 name, etc.
856
857 When called in a void context the installed_versions() method will
858 print out a formatted list of the hash contents, one per line.
859
860 Due to the potentially high memory cost and unknown risks of loading in
861 an unknown number of drivers that just happen to be installed on the
862 system, this method is not recommended for general use. Use
863 available_drivers() instead.
864
865 The installed_versions() method is primarily intended as a quick way to
866 see from the command line what's installed. For example:
867
868 perl -MDBI -e 'DBI->installed_versions'
869
870 The installed_versions() method was added in DBI 1.38.
871
872 "data_sources"
873
874 @ary = DBI->data_sources($driver);
875 @ary = DBI->data_sources($driver, \%attr);
876
877 Returns a list of data sources (databases) available via the named
878 driver. If $driver is empty or "undef", then the value of the
879 "DBI_DRIVER" environment variable is used.
880
881 The driver will be loaded if it hasn't been already. Note that if the
882 driver loading fails then data_sources() dies with an error message
883 that includes the string ""install_driver"" and the underlying problem.
884
885 Data sources are returned in a form suitable for passing to the
886 "connect" method (that is, they will include the ""dbi:$driver:""
887 prefix).
888
889 Note that many drivers have no way of knowing what data sources might
890 be available for it. These drivers return an empty or incomplete list
891 or may require driver-specific attributes.
892
893 There is also a data_sources() method defined for database handles.
894
895 "trace"
896
897 DBI->trace($trace_setting)
898 DBI->trace($trace_setting, $trace_filename)
899 DBI->trace($trace_setting, $trace_filehandle)
900 $trace_setting = DBI->trace;
901
902 The "DBI->trace" method sets the global default trace settings and
903 returns the previous trace settings. It can also be used to change
904 where the trace output is sent.
905
906 There's a similar method, "$h->trace", which sets the trace settings
907 for the specific handle it's called on.
908
909 See the "TRACING" section for full details about the DBI's powerful
910 tracing facilities.
911
912 "visit_handles"
913
914 DBI->visit_handles( $coderef );
915 DBI->visit_handles( $coderef, $info );
916
917 Where $coderef is a reference to a subroutine and $info is an arbitrary
918 value which, if undefined, defaults to a reference to an empty hash.
919 Returns $info.
920
921 For each installed driver handle, if any, $coderef is invoked as:
922
923 $coderef->($driver_handle, $info);
924
925 If the execution of $coderef returns a true value then
926 "visit_child_handles" is called on that child handle and passed the
927 returned value as $info.
928
929 For example:
930
931 my $info = $dbh->{Driver}->visit_child_handles(sub {
932 my ($h, $info) = @_;
933 ++$info->{ $h->{Type} }; # count types of handles (dr/db/st)
934 return $info; # visit kids
935 });
936
937 See also "visit_child_handles".
938
939 DBI Utility Functions
940 In addition to the DBI methods listed in the previous section, the DBI
941 package also provides several utility functions.
942
943 These can be imported into your code by listing them in the "use"
944 statement. For example:
945
946 use DBI qw(neat data_diff);
947
948 Alternatively, all these utility functions (except hash) can be
949 imported using the ":utils" import tag. For example:
950
951 use DBI qw(:utils);
952
953 "data_string_desc"
954
955 $description = data_string_desc($string);
956
957 Returns an informal description of the string. For example:
958
959 UTF8 off, ASCII, 42 characters 42 bytes
960 UTF8 off, non-ASCII, 42 characters 42 bytes
961 UTF8 on, non-ASCII, 4 characters 6 bytes
962 UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes
963 UTF8 off, undef
964
965 The initial "UTF8" on/off refers to Perl's internal SvUTF8 flag. If
966 $string has the SvUTF8 flag set but the sequence of bytes it contains
967 are not a valid UTF-8 encoding then data_string_desc() will report
968 "UTF8 on but INVALID encoding".
969
970 The "ASCII" vs "non-ASCII" portion shows "ASCII" if all the characters
971 in the string are ASCII (have code points <= 127).
972
973 The data_string_desc() function was added in DBI 1.46.
974
975 "data_string_diff"
976
977 $diff = data_string_diff($a, $b);
978
979 Returns an informal description of the first character difference
980 between the strings. If both $a and $b contain the same sequence of
981 characters then data_string_diff() returns an empty string. For
982 example:
983
984 Params a & b Result
985 ------------ ------
986 'aaa', 'aaa' ''
987 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b'
988 'aaa', undef 'String b is undef, string a has 3 characters'
989 'aaa', 'aa' 'String b truncated after 2 characters'
990
991 Unicode characters are reported in "\x{XXXX}" format. Unicode code
992 points in the range U+0800 to U+08FF are unassigned and most likely to
993 occur due to double-encoding. Characters in this range are reported as
994 "\x{08XX}='C'" where "C" is the corresponding latin-1 character.
995
996 The data_string_diff() function only considers logical characters and
997 not the underlying encoding. See "data_diff" for an alternative.
998
999 The data_string_diff() function was added in DBI 1.46.
1000
1001 "data_diff"
1002
1003 $diff = data_diff($a, $b);
1004 $diff = data_diff($a, $b, $logical);
1005
1006 Returns an informal description of the difference between two strings.
1007 It calls "data_string_desc" and "data_string_diff" and returns the
1008 combined results as a multi-line string.
1009
1010 For example, "data_diff("abc", "ab\x{263a}")" will return:
1011
1012 a: UTF8 off, ASCII, 3 characters 3 bytes
1013 b: UTF8 on, non-ASCII, 3 characters 5 bytes
1014 Strings differ at index 2: a[2]=c, b[2]=\x{263A}
1015
1016 If $a and $b are identical in both the characters they contain and
1017 their physical encoding then data_diff() returns an empty string. If
1018 $logical is true then physical encoding differences are ignored (but
1019 are still reported if there is a difference in the characters).
1020
1021 The data_diff() function was added in DBI 1.46.
1022
1023 "neat"
1024
1025 $str = neat($value);
1026 $str = neat($value, $maxlen);
1027
1028 Return a string containing a neat (and tidy) representation of the
1029 supplied value.
1030
1031 Strings will be quoted, although internal quotes will not be escaped.
1032 Values known to be numeric will be unquoted. Undefined (NULL) values
1033 will be shown as "undef" (without quotes).
1034
1035 If the string is flagged internally as utf8 then double quotes will be
1036 used, otherwise single quotes are used and unprintable characters will
1037 be replaced by dot (.).
1038
1039 For result strings longer than $maxlen the result string will be
1040 truncated to "$maxlen-4" and ""...'"" will be appended. If $maxlen is
1041 0 or "undef", it defaults to $DBI::neat_maxlen which, in turn, defaults
1042 to 400.
1043
1044 This function is designed to format values for human consumption. It
1045 is used internally by the DBI for "trace" output. It should typically
1046 not be used for formatting values for database use. (See also
1047 "quote".)
1048
1049 "neat_list"
1050
1051 $str = neat_list(\@listref, $maxlen, $field_sep);
1052
1053 Calls "neat" on each element of the list and returns a string
1054 containing the results joined with $field_sep. $field_sep defaults to
1055 ", ".
1056
1057 "looks_like_number"
1058
1059 @bool = looks_like_number(@array);
1060
1061 Returns true for each element that looks like a number. Returns false
1062 for each element that does not look like a number. Returns "undef" for
1063 each element that is undefined or empty.
1064
1065 "hash"
1066
1067 $hash_value = DBI::hash($buffer, $type);
1068
1069 Return a 32-bit integer 'hash' value corresponding to the contents of
1070 $buffer. The $type parameter selects which kind of hash algorithm
1071 should be used.
1072
1073 For the technically curious, type 0 (which is the default if $type
1074 isn't specified) is based on the Perl 5.1 hash except that the value is
1075 forced to be negative (for obscure historical reasons). Type 1 is the
1076 better "Fowler / Noll / Vo" (FNV) hash. See
1077 <http://www.isthe.com/chongo/tech/comp/fnv/> for more information.
1078 Both types are implemented in C and are very fast.
1079
1080 This function doesn't have much to do with databases, except that it
1081 can be handy to store hash values in a database.
1082
1083 DBI Dynamic Attributes
1084 Dynamic attributes are always associated with the last handle used
1085 (that handle is represented by $h in the descriptions below).
1086
1087 Where an attribute is equivalent to a method call, then refer to the
1088 method call for all related documentation.
1089
1090 Warning: these attributes are provided as a convenience but they do
1091 have limitations. Specifically, they have a short lifespan: because
1092 they are associated with the last handle used, they should only be used
1093 immediately after calling the method that "sets" them. If in any
1094 doubt, use the corresponding method call.
1095
1096 $DBI::err
1097
1098 Equivalent to "$h->err".
1099
1100 $DBI::errstr
1101
1102 Equivalent to "$h->errstr".
1103
1104 $DBI::state
1105
1106 Equivalent to "$h->state".
1107
1108 $DBI::rows
1109
1110 Equivalent to "$h->rows". Please refer to the documentation for the
1111 "rows" method.
1112
1113 $DBI::lasth
1114
1115 Returns the DBI object handle used for the most recent DBI method call.
1116 If the last DBI method call was a DESTROY then $DBI::lasth will return
1117 the handle of the parent of the destroyed handle, if there is one.
1118
1120 The following methods can be used by all types of DBI handles.
1121
1122 "err"
1123
1124 $rv = $h->err;
1125
1126 Returns the native database engine error code from the last driver
1127 method called. The code is typically an integer but you should not
1128 assume that.
1129
1130 The DBI resets $h->err to undef before almost all DBI method calls, so
1131 the value only has a short lifespan. Also, for most drivers, the
1132 statement handles share the same error variable as the parent database
1133 handle, so calling a method on one handle may reset the error on the
1134 related handles.
1135
1136 (Methods which don't reset err before being called include err() and
1137 errstr(), obviously, state(), rows(), func(), trace(), trace_msg(),
1138 ping(), and the tied hash attribute FETCH() and STORE() methods.)
1139
1140 If you need to test for specific error conditions and have your program
1141 be portable to different database engines, then you'll need to
1142 determine what the corresponding error codes are for all those engines
1143 and test for all of them.
1144
1145 The DBI uses the value of $DBI::stderr as the "err" value for internal
1146 errors. Drivers should also do likewise. The default value for
1147 $DBI::stderr is 2000000000.
1148
1149 A driver may return 0 from err() to indicate a warning condition after
1150 a method call. Similarly, a driver may return an empty string to
1151 indicate a 'success with information' condition. In both these cases
1152 the value is false but not undef. The errstr() and state() methods may
1153 be used to retrieve extra information in these cases.
1154
1155 See "set_err" for more information.
1156
1157 "errstr"
1158
1159 $str = $h->errstr;
1160
1161 Returns the native database engine error message from the last DBI
1162 method called. This has the same lifespan issues as the "err" method
1163 described above.
1164
1165 The returned string may contain multiple messages separated by newline
1166 characters.
1167
1168 The errstr() method should not be used to test for errors, use err()
1169 for that, because drivers may return 'success with information' or
1170 warning messages via errstr() for methods that have not 'failed'.
1171
1172 See "set_err" for more information.
1173
1174 "state"
1175
1176 $str = $h->state;
1177
1178 Returns a state code in the standard SQLSTATE five character format.
1179 Note that the specific success code 00000 is translated to any empty
1180 string (false). If the driver does not support SQLSTATE (and most
1181 don't), then state() will return "S1000" (General Error) for all
1182 errors.
1183
1184 The driver is free to return any value via "state", e.g., warning
1185 codes, even if it has not declared an error by returning a true value
1186 via the "err" method described above.
1187
1188 The state() method should not be used to test for errors, use err() for
1189 that, because drivers may return a 'success with information' or
1190 warning state code via state() for methods that have not 'failed'.
1191
1192 "set_err"
1193
1194 $rv = $h->set_err($err, $errstr);
1195 $rv = $h->set_err($err, $errstr, $state);
1196 $rv = $h->set_err($err, $errstr, $state, $method);
1197 $rv = $h->set_err($err, $errstr, $state, $method, $rv);
1198
1199 Set the "err", "errstr", and "state" values for the handle. This
1200 method is typically only used by DBI drivers and DBI subclasses.
1201
1202 If the "HandleSetErr" attribute holds a reference to a subroutine it is
1203 called first. The subroutine can alter the $err, $errstr, $state, and
1204 $method values. See "HandleSetErr" for full details. If the subroutine
1205 returns a true value then the handle "err", "errstr", and "state"
1206 values are not altered and set_err() returns an empty list (it normally
1207 returns $rv which defaults to undef, see below).
1208
1209 Setting "err" to a true value indicates an error and will trigger the
1210 normal DBI error handling mechanisms, such as "RaiseError" and
1211 "HandleError", if they are enabled, when execution returns from the DBI
1212 back to the application.
1213
1214 Setting "err" to "" indicates an 'information' state, and setting it to
1215 "0" indicates a 'warning' state. Setting "err" to "undef" also sets
1216 "errstr" to undef, and "state" to "", irrespective of the values of the
1217 $errstr and $state parameters.
1218
1219 The $method parameter provides an alternate method name for the
1220 "RaiseError"/"PrintError"/"PrintWarn" error string instead of the
1221 fairly unhelpful '"set_err"'.
1222
1223 The "set_err" method normally returns undef. The $rv parameter
1224 provides an alternate return value.
1225
1226 Some special rules apply if the "err" or "errstr" values for the handle
1227 are already set...
1228
1229 If "errstr" is true then: "" [err was %s now %s]"" is appended if $err
1230 is true and "err" is already true and the new err value differs from
1231 the original one. Similarly "" [state was %s now %s]"" is appended if
1232 $state is true and "state" is already true and the new state value
1233 differs from the original one. Finally ""\n"" and the new $errstr are
1234 appended if $errstr differs from the existing errstr value. Obviously
1235 the %s's above are replaced by the corresponding values.
1236
1237 The handle "err" value is set to $err if: $err is true; or handle "err"
1238 value is undef; or $err is defined and the length is greater than the
1239 handle "err" length. The effect is that an 'information' state only
1240 overrides undef; a 'warning' overrides undef or 'information', and an
1241 'error' state overrides anything.
1242
1243 The handle "state" value is set to $state if $state is true and the
1244 handle "err" value was set (by the rules above).
1245
1246 Support for warning and information states was added in DBI 1.41.
1247
1248 "trace"
1249
1250 $h->trace($trace_settings);
1251 $h->trace($trace_settings, $trace_filename);
1252 $trace_settings = $h->trace;
1253
1254 The trace() method is used to alter the trace settings for a handle
1255 (and any future children of that handle). It can also be used to
1256 change where the trace output is sent.
1257
1258 There's a similar method, "DBI->trace", which sets the global default
1259 trace settings.
1260
1261 See the "TRACING" section for full details about the DBI's powerful
1262 tracing facilities.
1263
1264 "trace_msg"
1265
1266 $h->trace_msg($message_text);
1267 $h->trace_msg($message_text, $min_level);
1268
1269 Writes $message_text to the trace file if the trace level is greater
1270 than or equal to $min_level (which defaults to 1). Can also be called
1271 as "DBI->trace_msg($msg)".
1272
1273 See "TRACING" for more details.
1274
1275 "func"
1276
1277 $h->func(@func_arguments, $func_name) or die ...;
1278
1279 The "func" method can be used to call private non-standard and non-
1280 portable methods implemented by the driver. Note that the function name
1281 is given as the last argument.
1282
1283 It's also important to note that the func() method does not clear a
1284 previous error ($DBI::err etc.) and it does not trigger automatic error
1285 detection (RaiseError etc.) so you must check the return status and/or
1286 $h->err to detect errors.
1287
1288 (This method is not directly related to calling stored procedures.
1289 Calling stored procedures is currently not defined by the DBI. Some
1290 drivers, such as DBD::Oracle, support it in non-portable ways. See
1291 driver documentation for more details.)
1292
1293 See also install_method() in DBI::DBD for how you can avoid needing to
1294 use func() and gain direct access to driver-private methods.
1295
1296 "can"
1297
1298 $is_implemented = $h->can($method_name);
1299
1300 Returns true if $method_name is implemented by the driver or a default
1301 method is provided by the DBI. It returns false where a driver hasn't
1302 implemented a method and the default method is provided by the DBI is
1303 just an empty stub.
1304
1305 "parse_trace_flags"
1306
1307 $trace_settings_integer = $h->parse_trace_flags($trace_settings);
1308
1309 Parses a string containing trace settings and returns the corresponding
1310 integer value used internally by the DBI and drivers.
1311
1312 The $trace_settings argument is a string containing a trace level
1313 between 0 and 15 and/or trace flag names separated by vertical bar
1314 (""|"") or comma ("","") characters. For example: "SQL|3|foo".
1315
1316 It uses the parse_trace_flag() method, described below, to process the
1317 individual trace flag names.
1318
1319 The parse_trace_flags() method was added in DBI 1.42.
1320
1321 "parse_trace_flag"
1322
1323 $bit_flag = $h->parse_trace_flag($trace_flag_name);
1324
1325 Returns the bit flag corresponding to the trace flag name in
1326 $trace_flag_name. Drivers are expected to override this method and
1327 check if $trace_flag_name is a driver specific trace flags and, if not,
1328 then call the DBI's default parse_trace_flag().
1329
1330 The parse_trace_flag() method was added in DBI 1.42.
1331
1332 "private_attribute_info"
1333
1334 $hash_ref = $h->private_attribute_info();
1335
1336 Returns a reference to a hash whose keys are the names of driver-
1337 private attributes available for the kind of handle (driver, database,
1338 statement) that the method was called on.
1339
1340 For example, the return value when called with a DBD::Sybase $dbh could
1341 look like this:
1342
1343 {
1344 syb_dynamic_supported => undef,
1345 syb_oc_version => undef,
1346 syb_server_version => undef,
1347 syb_server_version_string => undef,
1348 }
1349
1350 and when called with a DBD::Sybase $sth they could look like this:
1351
1352 {
1353 syb_types => undef,
1354 syb_proc_status => undef,
1355 syb_result_type => undef,
1356 }
1357
1358 The values should be undef. Meanings may be assigned to particular
1359 values in future.
1360
1361 "swap_inner_handle"
1362
1363 $rc = $h1->swap_inner_handle( $h2 );
1364 $rc = $h1->swap_inner_handle( $h2, $allow_reparent );
1365
1366 Brain transplants for handles. You don't need to know about this unless
1367 you want to become a handle surgeon.
1368
1369 A DBI handle is a reference to a tied hash. A tied hash has an inner
1370 hash that actually holds the contents. The swap_inner_handle() method
1371 swaps the inner hashes between two handles. The $h1 and $h2 handles
1372 still point to the same tied hashes, but what those hashes are tied to
1373 has been swapped. In effect $h1 becomes $h2 and vice-versa. This is
1374 powerful stuff, expect problems. Use with care.
1375
1376 As a small safety measure, the two handles, $h1 and $h2, have to share
1377 the same parent unless $allow_reparent is true.
1378
1379 The swap_inner_handle() method was added in DBI 1.44.
1380
1381 Here's a quick kind of 'diagram' as a worked example to help think
1382 about what's happening:
1383
1384 Original state:
1385 dbh1o -> dbh1i
1386 sthAo -> sthAi(dbh1i)
1387 dbh2o -> dbh2i
1388
1389 swap_inner_handle dbh1o with dbh2o:
1390 dbh2o -> dbh1i
1391 sthAo -> sthAi(dbh1i)
1392 dbh1o -> dbh2i
1393
1394 create new sth from dbh1o:
1395 dbh2o -> dbh1i
1396 sthAo -> sthAi(dbh1i)
1397 dbh1o -> dbh2i
1398 sthBo -> sthBi(dbh2i)
1399
1400 swap_inner_handle sthAo with sthBo:
1401 dbh2o -> dbh1i
1402 sthBo -> sthAi(dbh1i)
1403 dbh1o -> dbh2i
1404 sthAo -> sthBi(dbh2i)
1405
1406 "visit_child_handles"
1407
1408 $h->visit_child_handles( $coderef );
1409 $h->visit_child_handles( $coderef, $info );
1410
1411 Where $coderef is a reference to a subroutine and $info is an arbitrary
1412 value which, if undefined, defaults to a reference to an empty hash.
1413 Returns $info.
1414
1415 For each child handle of $h, if any, $coderef is invoked as:
1416
1417 $coderef->($child_handle, $info);
1418
1419 If the execution of $coderef returns a true value then
1420 "visit_child_handles" is called on that child handle and passed the
1421 returned value as $info.
1422
1423 For example:
1424
1425 # count database connections with names (DSN) matching a pattern
1426 my $connections = 0;
1427 $dbh->{Driver}->visit_child_handles(sub {
1428 my ($h, $info) = @_;
1429 ++$connections if $h->{Name} =~ /foo/;
1430 return 0; # don't visit kids
1431 })
1432
1433 See also "visit_handles".
1434
1436 These attributes are common to all types of DBI handles.
1437
1438 Some attributes are inherited by child handles. That is, the value of
1439 an inherited attribute in a newly created statement handle is the same
1440 as the value in the parent database handle. Changes to attributes in
1441 the new statement handle do not affect the parent database handle and
1442 changes to the database handle do not affect existing statement
1443 handles, only future ones.
1444
1445 Attempting to set or get the value of an unknown attribute generates a
1446 warning, except for private driver specific attributes (which all have
1447 names starting with a lowercase letter).
1448
1449 Example:
1450
1451 $h->{AttributeName} = ...; # set/write
1452 ... = $h->{AttributeName}; # get/read
1453
1454 "Warn" (boolean, inherited)
1455
1456 The "Warn" attribute enables useful warnings for certain bad practices.
1457 It is enabled by default and should only be disabled in rare
1458 circumstances. Since warnings are generated using the Perl "warn"
1459 function, they can be intercepted using the Perl $SIG{__WARN__} hook.
1460
1461 The "Warn" attribute is not related to the "PrintWarn" attribute.
1462
1463 "Active" (boolean, read-only)
1464
1465 The "Active" attribute is true if the handle object is "active". This
1466 is rarely used in applications. The exact meaning of active is somewhat
1467 vague at the moment. For a database handle it typically means that the
1468 handle is connected to a database ("$dbh->disconnect" sets "Active"
1469 off). For a statement handle it typically means that the handle is a
1470 "SELECT" that may have more data to fetch. (Fetching all the data or
1471 calling "$sth->finish" sets "Active" off.)
1472
1473 "Executed" (boolean)
1474
1475 The "Executed" attribute is true if the handle object has been
1476 "executed". Currently only the $dbh do() method and the $sth
1477 execute(), execute_array(), and execute_for_fetch() methods set the
1478 "Executed" attribute.
1479
1480 When it's set on a handle it is also set on the parent handle at the
1481 same time. So calling execute() on a $sth also sets the "Executed"
1482 attribute on the parent $dbh.
1483
1484 The "Executed" attribute for a database handle is cleared by the
1485 commit() and rollback() methods (even if they fail). The "Executed"
1486 attribute of a statement handle is not cleared by the DBI under any
1487 circumstances and so acts as a permanent record of whether the
1488 statement handle was ever used.
1489
1490 The "Executed" attribute was added in DBI 1.41.
1491
1492 "Kids" (integer, read-only)
1493
1494 For a driver handle, "Kids" is the number of currently existing
1495 database handles that were created from that driver handle. For a
1496 database handle, "Kids" is the number of currently existing statement
1497 handles that were created from that database handle. For a statement
1498 handle, the value is zero.
1499
1500 "ActiveKids" (integer, read-only)
1501
1502 Like "Kids", but only counting those that are "Active" (as above).
1503
1504 "CachedKids" (hash ref)
1505
1506 For a database handle, "CachedKids" returns a reference to the cache
1507 (hash) of statement handles created by the "prepare_cached" method.
1508 For a driver handle, returns a reference to the cache (hash) of
1509 database handles created by the "connect_cached" method.
1510
1511 "Type" (scalar, read-only)
1512
1513 The "Type" attribute identifies the type of a DBI handle. Returns "dr"
1514 for driver handles, "db" for database handles and "st" for statement
1515 handles.
1516
1517 "ChildHandles" (array ref)
1518
1519 The ChildHandles attribute contains a reference to an array of all the
1520 handles created by this handle which are still accessible. The
1521 contents of the array are weak-refs and will become undef when the
1522 handle goes out of scope.
1523
1524 "ChildHandles" returns undef if your perl version does not support weak
1525 references (check the Scalar::Util module). The referenced array
1526 returned should be treated as read-only.
1527
1528 For example, to enumerate all driver handles, database handles and
1529 statement handles:
1530
1531 sub show_child_handles {
1532 my ($h, $level) = @_;
1533 printf "%sh %s %s\n", $h->{Type}, "\t" x $level, $h;
1534 show_child_handles($_, $level + 1)
1535 for (grep { defined } @{$h->{ChildHandles}});
1536 }
1537
1538 my %drivers = DBI->installed_drivers();
1539 show_child_handles($_, 0) for (values %drivers);
1540
1541 "CompatMode" (boolean, inherited)
1542
1543 The "CompatMode" attribute is used by emulation layers (such as
1544 Oraperl) to enable compatible behaviour in the underlying driver (e.g.,
1545 DBD::Oracle) for this handle. Not normally set by application code.
1546
1547 It also has the effect of disabling the 'quick FETCH' of attribute
1548 values from the handles attribute cache. So all attribute values are
1549 handled by the drivers own FETCH method. This makes them slightly
1550 slower but is useful for special-purpose drivers like DBD::Multiplex.
1551
1552 "InactiveDestroy" (boolean)
1553
1554 The default value, false, means a handle will be fully destroyed as
1555 normal when the last reference to it is removed, just as you'd expect.
1556
1557 If set true then the handle will be treated by the DESTROY as if it was
1558 no longer Active, and so the database engine related effects of
1559 DESTROYing a handle will be skipped.
1560
1561 Think of the name as meaning 'treat the handle as not-Active in the
1562 DESTROY method'.
1563
1564 For a database handle, this attribute does not disable an explicit call
1565 to the disconnect method, only the implicit call from DESTROY that
1566 happens if the handle is still marked as "Active".
1567
1568 This attribute is specifically designed for use in Unix applications
1569 that "fork" child processes. Either the parent or the child process,
1570 but not both, should set "InactiveDestroy" true on all their shared
1571 handles. (Note that some databases, including Oracle, don't support
1572 passing a database connection across a fork.)
1573
1574 To help tracing applications using fork the process id is shown in the
1575 trace log whenever a DBI or handle trace() method is called. The
1576 process id also shown for every method call if the DBI trace level (not
1577 handle trace level) is set high enough to show the trace from the DBI's
1578 method dispatcher, e.g. >= 9.
1579
1580 "PrintWarn" (boolean, inherited)
1581
1582 The "PrintWarn" attribute controls the printing of warnings recorded by
1583 the driver. When set to a true value the DBI will check method calls
1584 to see if a warning condition has been set. If so, the DBI will
1585 effectively do a "warn("$class $method warning: $DBI::errstr")" where
1586 $class is the driver class and $method is the name of the method which
1587 failed. E.g.,
1588
1589 DBD::Oracle::db execute warning: ... warning text here ...
1590
1591 By default, "DBI->connect" sets "PrintWarn" "on" if $^W is true, i.e.,
1592 perl is running with warnings enabled.
1593
1594 If desired, the warnings can be caught and processed using a
1595 $SIG{__WARN__} handler or modules like CGI::Carp and CGI::ErrorWrap.
1596
1597 See also "set_err" for how warnings are recorded and "HandleSetErr" for
1598 how to influence it.
1599
1600 Fetching the full details of warnings can require an extra round-trip
1601 to the database server for some drivers. In which case the driver may
1602 opt to only fetch the full details of warnings if the "PrintWarn"
1603 attribute is true. If "PrintWarn" is false then these drivers should
1604 still indicate the fact that there were warnings by setting the warning
1605 string to, for example: "3 warnings".
1606
1607 "PrintError" (boolean, inherited)
1608
1609 The "PrintError" attribute can be used to force errors to generate
1610 warnings (using "warn") in addition to returning error codes in the
1611 normal way. When set "on", any method which results in an error
1612 occurring will cause the DBI to effectively do a "warn("$class $method
1613 failed: $DBI::errstr")" where $class is the driver class and $method is
1614 the name of the method which failed. E.g.,
1615
1616 DBD::Oracle::db prepare failed: ... error text here ...
1617
1618 By default, "DBI->connect" sets "PrintError" "on".
1619
1620 If desired, the warnings can be caught and processed using a
1621 $SIG{__WARN__} handler or modules like CGI::Carp and CGI::ErrorWrap.
1622
1623 "RaiseError" (boolean, inherited)
1624
1625 The "RaiseError" attribute can be used to force errors to raise
1626 exceptions rather than simply return error codes in the normal way. It
1627 is "off" by default. When set "on", any method which results in an
1628 error will cause the DBI to effectively do a "die("$class $method
1629 failed: $DBI::errstr")", where $class is the driver class and $method
1630 is the name of the method that failed. E.g.,
1631
1632 DBD::Oracle::db prepare failed: ... error text here ...
1633
1634 If you turn "RaiseError" on then you'd normally turn "PrintError" off.
1635 If "PrintError" is also on, then the "PrintError" is done first
1636 (naturally).
1637
1638 Typically "RaiseError" is used in conjunction with "eval { ... }" to
1639 catch the exception that's been thrown and followed by an "if ($@) {
1640 ... }" block to handle the caught exception. For example:
1641
1642 eval {
1643 ...
1644 $sth->execute();
1645 ...
1646 };
1647 if ($@) {
1648 # $sth->err and $DBI::err will be true if error was from DBI
1649 warn $@; # print the error
1650 ... # do whatever you need to deal with the error
1651 }
1652
1653 In that eval block the $DBI::lasth variable can be useful for diagnosis
1654 and reporting if you can't be sure which handle triggered the error.
1655 For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
1656
1657 See also "Transactions".
1658
1659 If you want to temporarily turn "RaiseError" off (inside a library
1660 function that is likely to fail, for example), the recommended way is
1661 like this:
1662
1663 {
1664 local $h->{RaiseError}; # localize and turn off for this block
1665 ...
1666 }
1667
1668 The original value will automatically and reliably be restored by Perl,
1669 regardless of how the block is exited. The same logic applies to other
1670 attributes, including "PrintError".
1671
1672 "HandleError" (code ref, inherited)
1673
1674 The "HandleError" attribute can be used to provide your own alternative
1675 behaviour in case of errors. If set to a reference to a subroutine then
1676 that subroutine is called when an error is detected (at the same point
1677 that "RaiseError" and "PrintError" are handled).
1678
1679 The subroutine is called with three parameters: the error message
1680 string that "RaiseError" and "PrintError" would use, the DBI handle
1681 being used, and the first value being returned by the method that
1682 failed (typically undef).
1683
1684 If the subroutine returns a false value then the "RaiseError" and/or
1685 "PrintError" attributes are checked and acted upon as normal.
1686
1687 For example, to "die" with a full stack trace for any error:
1688
1689 use Carp;
1690 $h->{HandleError} = sub { confess(shift) };
1691
1692 Or to turn errors into exceptions:
1693
1694 use Exception; # or your own favourite exception module
1695 $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
1696
1697 It is possible to 'stack' multiple HandleError handlers by using
1698 closures:
1699
1700 sub your_subroutine {
1701 my $previous_handler = $h->{HandleError};
1702 $h->{HandleError} = sub {
1703 return 1 if $previous_handler and &$previous_handler(@_);
1704 ... your code here ...
1705 };
1706 }
1707
1708 Using a "my" inside a subroutine to store the previous "HandleError"
1709 value is important. See perlsub and perlref for more information about
1710 closures.
1711
1712 It is possible for "HandleError" to alter the error message that will
1713 be used by "RaiseError" and "PrintError" if it returns false. It can
1714 do that by altering the value of $_[0]. This example appends a stack
1715 trace to all errors and, unlike the previous example using
1716 Carp::confess, this will work "PrintError" as well as "RaiseError":
1717
1718 $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; };
1719
1720 It is also possible for "HandleError" to hide an error, to a limited
1721 degree, by using "set_err" to reset $DBI::err and $DBI::errstr, and
1722 altering the return value of the failed method. For example:
1723
1724 $h->{HandleError} = sub {
1725 return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/;
1726 return 0 unless $_[1]->err == 1234; # the error to 'hide'
1727 $h->set_err(undef,undef); # turn off the error
1728 $_[2] = [ ... ]; # supply alternative return value
1729 return 1;
1730 };
1731
1732 This only works for methods which return a single value and is hard to
1733 make reliable (avoiding infinite loops, for example) and so isn't
1734 recommended for general use! If you find a good use for it then please
1735 let me know.
1736
1737 "HandleSetErr" (code ref, inherited)
1738
1739 The "HandleSetErr" attribute can be used to intercept the setting of
1740 handle "err", "errstr", and "state" values. If set to a reference to a
1741 subroutine then that subroutine is called whenever set_err() is called,
1742 typically by the driver or a subclass.
1743
1744 The subroutine is called with five arguments, the first five that were
1745 passed to set_err(): the handle, the "err", "errstr", and "state"
1746 values being set, and the method name. These can be altered by changing
1747 the values in the @_ array. The return value affects set_err()
1748 behaviour, see "set_err" for details.
1749
1750 It is possible to 'stack' multiple HandleSetErr handlers by using
1751 closures. See "HandleError" for an example.
1752
1753 The "HandleSetErr" and "HandleError" subroutines differ in subtle but
1754 significant ways. HandleError is only invoked at the point where the
1755 DBI is about to return to the application with "err" set true. It's
1756 not invoked by the failure of a method that's been called by another
1757 DBI method. HandleSetErr, on the other hand, is called whenever
1758 set_err() is called with a defined "err" value, even if false. So it's
1759 not just for errors, despite the name, but also warn and info states.
1760 The set_err() method, and thus HandleSetErr, may be called multiple
1761 times within a method and is usually invoked from deep within driver
1762 code.
1763
1764 In theory a driver can use the return value from HandleSetErr via
1765 set_err() to decide whether to continue or not. If set_err() returns an
1766 empty list, indicating that the HandleSetErr code has 'handled' the
1767 'error', the driver could then continue instead of failing (if that's a
1768 reasonable thing to do). This isn't excepted to be common and any such
1769 cases should be clearly marked in the driver documentation and
1770 discussed on the dbi-dev mailing list.
1771
1772 The "HandleSetErr" attribute was added in DBI 1.41.
1773
1774 "ErrCount" (unsigned integer)
1775
1776 The "ErrCount" attribute is incremented whenever the set_err() method
1777 records an error. It isn't incremented by warnings or information
1778 states. It is not reset by the DBI at any time.
1779
1780 The "ErrCount" attribute was added in DBI 1.41. Older drivers may not
1781 have been updated to use set_err() to record errors and so this
1782 attribute may not be incremented when using them.
1783
1784 "ShowErrorStatement" (boolean, inherited)
1785
1786 The "ShowErrorStatement" attribute can be used to cause the relevant
1787 Statement text to be appended to the error messages generated by the
1788 "RaiseError", "PrintError", and "PrintWarn" attributes. Only applies
1789 to errors on statement handles plus the prepare(), do(), and the
1790 various "select*()" database handle methods. (The exact format of the
1791 appended text is subject to change.)
1792
1793 If "$h->{ParamValues}" returns a hash reference of parameter
1794 (placeholder) values then those are formatted and appended to the end
1795 of the Statement text in the error message.
1796
1797 "TraceLevel" (integer, inherited)
1798
1799 The "TraceLevel" attribute can be used as an alternative to the "trace"
1800 method to set the DBI trace level and trace flags for a specific
1801 handle. See "TRACING" for more details.
1802
1803 The "TraceLevel" attribute is especially useful combined with "local"
1804 to alter the trace settings for just a single block of code.
1805
1806 "FetchHashKeyName" (string, inherited)
1807
1808 The "FetchHashKeyName" attribute is used to specify whether the
1809 fetchrow_hashref() method should perform case conversion on the field
1810 names used for the hash keys. For historical reasons it defaults to
1811 '"NAME"' but it is recommended to set it to '"NAME_lc"' (convert to
1812 lower case) or '"NAME_uc"' (convert to upper case) according to your
1813 preference. It can only be set for driver and database handles. For
1814 statement handles the value is frozen when prepare() is called.
1815
1816 "ChopBlanks" (boolean, inherited)
1817
1818 The "ChopBlanks" attribute can be used to control the trimming of
1819 trailing space characters from fixed width character (CHAR) fields. No
1820 other field types are affected, even where field values have trailing
1821 spaces.
1822
1823 The default is false (although it is possible that the default may
1824 change). Applications that need specific behaviour should set the
1825 attribute as needed.
1826
1827 Drivers are not required to support this attribute, but any driver
1828 which does not support it must arrange to return "undef" as the
1829 attribute value.
1830
1831 "LongReadLen" (unsigned integer, inherited)
1832
1833 The "LongReadLen" attribute may be used to control the maximum length
1834 of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver
1835 will read from the database automatically when it fetches each row of
1836 data.
1837
1838 The "LongReadLen" attribute only relates to fetching and reading long
1839 values; it is not involved in inserting or updating them.
1840
1841 A value of 0 means not to automatically fetch any long data. Drivers
1842 may return undef or an empty string for long fields when "LongReadLen"
1843 is 0.
1844
1845 The default is typically 0 (zero) or 80 bytes but may vary between
1846 drivers. Applications fetching long fields should set this value to
1847 slightly larger than the longest long field value to be fetched.
1848
1849 Some databases return some long types encoded as pairs of hex digits.
1850 For these types, "LongReadLen" relates to the underlying data length
1851 and not the doubled-up length of the encoded string.
1852
1853 Changing the value of "LongReadLen" for a statement handle after it has
1854 been "prepare"'d will typically have no effect, so it's common to set
1855 "LongReadLen" on the $dbh before calling "prepare".
1856
1857 For most drivers the value used here has a direct effect on the memory
1858 used by the statement handle while it's active, so don't be too
1859 generous. If you can't be sure what value to use you could execute an
1860 extra select statement to determine the longest value. For example:
1861
1862 $dbh->{LongReadLen} = $dbh->selectrow_array(qq{
1863 SELECT MAX(OCTET_LENGTH(long_column_name))
1864 FROM table WHERE ...
1865 });
1866 $sth = $dbh->prepare(qq{
1867 SELECT long_column_name, ... FROM table WHERE ...
1868 });
1869
1870 You may need to take extra care if the table can be modified between
1871 the first select and the second being executed. You may also need to
1872 use a different function if OCTET_LENGTH() does not work for long types
1873 in your database. For example, for Sybase use DATALENGTH() and for
1874 Oracle use LENGTHB().
1875
1876 See also "LongTruncOk" for information on truncation of long types.
1877
1878 "LongTruncOk" (boolean, inherited)
1879
1880 The "LongTruncOk" attribute may be used to control the effect of
1881 fetching a long field value which has been truncated (typically because
1882 it's longer than the value of the "LongReadLen" attribute).
1883
1884 By default, "LongTruncOk" is false and so fetching a long value that
1885 needs to be truncated will cause the fetch to fail. (Applications
1886 should always be sure to check for errors after a fetch loop in case an
1887 error, such as a divide by zero or long field truncation, caused the
1888 fetch to terminate prematurely.)
1889
1890 If a fetch fails due to a long field truncation when "LongTruncOk" is
1891 false, many drivers will allow you to continue fetching further rows.
1892
1893 See also "LongReadLen".
1894
1895 "TaintIn" (boolean, inherited)
1896
1897 If the "TaintIn" attribute is set to a true value and Perl is running
1898 in taint mode (e.g., started with the "-T" option), then all the
1899 arguments to most DBI method calls are checked for being tainted. This
1900 may change.
1901
1902 The attribute defaults to off, even if Perl is in taint mode. See
1903 perlsec for more about taint mode. If Perl is not running in taint
1904 mode, this attribute has no effect.
1905
1906 When fetching data that you trust you can turn off the TaintIn
1907 attribute, for that statement handle, for the duration of the fetch
1908 loop.
1909
1910 The "TaintIn" attribute was added in DBI 1.31.
1911
1912 "TaintOut" (boolean, inherited)
1913
1914 If the "TaintOut" attribute is set to a true value and Perl is running
1915 in taint mode (e.g., started with the "-T" option), then most data
1916 fetched from the database is considered tainted. This may change.
1917
1918 The attribute defaults to off, even if Perl is in taint mode. See
1919 perlsec for more about taint mode. If Perl is not running in taint
1920 mode, this attribute has no effect.
1921
1922 When fetching data that you trust you can turn off the TaintOut
1923 attribute, for that statement handle, for the duration of the fetch
1924 loop.
1925
1926 Currently only fetched data is tainted. It is possible that the results
1927 of other DBI method calls, and the value of fetched attributes, may
1928 also be tainted in future versions. That change may well break your
1929 applications unless you take great care now. If you use DBI Taint mode,
1930 please report your experience and any suggestions for changes.
1931
1932 The "TaintOut" attribute was added in DBI 1.31.
1933
1934 "Taint" (boolean, inherited)
1935
1936 The "Taint" attribute is a shortcut for "TaintIn" and "TaintOut" (it is
1937 also present for backwards compatibility).
1938
1939 Setting this attribute sets both "TaintIn" and "TaintOut", and
1940 retrieving it returns a true value if and only if "TaintIn" and
1941 "TaintOut" are both set to true values.
1942
1943 "Profile" (inherited)
1944
1945 The "Profile" attribute enables the collection and reporting of method
1946 call timing statistics. See the DBI::Profile module documentation for
1947 much more detail.
1948
1949 The "Profile" attribute was added in DBI 1.24.
1950
1951 "ReadOnly" (boolean, inherited)
1952
1953 An application can set the "ReadOnly" attribute of a handle to a true
1954 value to indicate that it will not be attempting to make any changes
1955 using that handle or any children of it.
1956
1957 Note that the exact definition of 'read only' is rather fuzzy. For
1958 more details see the documentation for the driver you're using.
1959
1960 If the driver can make the handle truly read-only then it should
1961 (unless doing so would have unpleasant side effect, like changing the
1962 consistency level from per-statement to per-session). Otherwise the
1963 attribute is simply advisory.
1964
1965 A driver can set the "ReadOnly" attribute itself to indicate that the
1966 data it is connected to cannot be changed for some reason.
1967
1968 Library modules and proxy drivers can use the attribute to influence
1969 their behavior. For example, the DBD::Gofer driver considers the
1970 "ReadOnly" attribute when making a decision about whether to retry an
1971 operation that failed.
1972
1973 The attribute should be set to 1 or 0 (or undef). Other values are
1974 reserved.
1975
1976 "private_your_module_name_*"
1977
1978 The DBI provides a way to store extra information in a DBI handle as
1979 "private" attributes. The DBI will allow you to store and retrieve any
1980 attribute which has a name starting with ""private_"".
1981
1982 It is strongly recommended that you use just one private attribute
1983 (e.g., use a hash ref) and give it a long and unambiguous name that
1984 includes the module or application name that the attribute relates to
1985 (e.g., ""private_YourFullModuleName_thingy"").
1986
1987 Because of the way the Perl tie mechanism works you cannot reliably use
1988 the "||=" operator directly to initialise the attribute, like this:
1989
1990 my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG
1991
1992 you should use a two step approach like this:
1993
1994 my $foo = $dbh->{private_yourmodname_foo};
1995 $foo ||= $dbh->{private_yourmodname_foo} = { ... };
1996
1997 This attribute is primarily of interest to people sub-classing DBI, or
1998 for applications to piggy-back extra information onto DBI handles.
1999
2001 This section covers the methods and attributes associated with database
2002 handles.
2003
2004 Database Handle Methods
2005 The following methods are specified for DBI database handles:
2006
2007 "clone"
2008
2009 $new_dbh = $dbh->clone();
2010 $new_dbh = $dbh->clone(\%attr);
2011
2012 The "clone" method duplicates the $dbh connection by connecting with
2013 the same parameters ($dsn, $user, $password) as originally used.
2014
2015 The attributes for the cloned connect are the same as those used for
2016 the original connect, with some other attribute merged over them
2017 depending on the \%attr parameter.
2018
2019 If \%attr is given then the attributes it contains are merged into the
2020 original attributes and override any with the same names. Effectively
2021 the same as doing:
2022
2023 %attribues_used = ( %original_attributes, %attr );
2024
2025 If \%attr is not given then it defaults to a hash containing all the
2026 attributes in the attribute cache of $dbh excluding any non-code
2027 references, plus the main boolean attributes (RaiseError, PrintError,
2028 AutoCommit, etc.). This behaviour is subject to change.
2029
2030 The clone method can be used even if the database handle is
2031 disconnected.
2032
2033 The "clone" method was added in DBI 1.33. It is very new and likely to
2034 change.
2035
2036 "data_sources"
2037
2038 @ary = $dbh->data_sources();
2039 @ary = $dbh->data_sources(\%attr);
2040
2041 Returns a list of data sources (databases) available via the $dbh
2042 driver's data_sources() method, plus any extra data sources that the
2043 driver can discover via the connected $dbh. Typically the extra data
2044 sources are other databases managed by the same server process that the
2045 $dbh is connected to.
2046
2047 Data sources are returned in a form suitable for passing to the
2048 "connect" method (that is, they will include the ""dbi:$driver:""
2049 prefix).
2050
2051 The data_sources() method, for a $dbh, was added in DBI 1.38.
2052
2053 "do"
2054
2055 $rows = $dbh->do($statement) or die $dbh->errstr;
2056 $rows = $dbh->do($statement, \%attr) or die $dbh->errstr;
2057 $rows = $dbh->do($statement, \%attr, @bind_values) or die ...
2058
2059 Prepare and execute a single statement. Returns the number of rows
2060 affected or "undef" on error. A return value of "-1" means the number
2061 of rows is not known, not applicable, or not available.
2062
2063 This method is typically most useful for non-"SELECT" statements that
2064 either cannot be prepared in advance (due to a limitation of the
2065 driver) or do not need to be executed repeatedly. It should not be used
2066 for "SELECT" statements because it does not return a statement handle
2067 (so you can't fetch any data).
2068
2069 The default "do" method is logically similar to:
2070
2071 sub do {
2072 my($dbh, $statement, $attr, @bind_values) = @_;
2073 my $sth = $dbh->prepare($statement, $attr) or return undef;
2074 $sth->execute(@bind_values) or return undef;
2075 my $rows = $sth->rows;
2076 ($rows == 0) ? "0E0" : $rows; # always return true if no error
2077 }
2078
2079 For example:
2080
2081 my $rows_deleted = $dbh->do(q{
2082 DELETE FROM table
2083 WHERE status = ?
2084 }, undef, 'DONE') or die $dbh->errstr;
2085
2086 Using placeholders and @bind_values with the "do" method can be useful
2087 because it avoids the need to correctly quote any variables in the
2088 $statement. But if you'll be executing the statement many times then
2089 it's more efficient to "prepare" it once and call "execute" many times
2090 instead.
2091
2092 The "q{...}" style quoting used in this example avoids clashing with
2093 quotes that may be used in the SQL statement. Use the double-quote-like
2094 "qq{...}" operator if you want to interpolate variables into the
2095 string. See "Quote and Quote-like Operators" in perlop for more
2096 details.
2097
2098 "last_insert_id"
2099
2100 $rv = $dbh->last_insert_id($catalog, $schema, $table, $field);
2101 $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
2102
2103 Returns a value 'identifying' the row just inserted, if possible.
2104 Typically this would be a value assigned by the database server to a
2105 column with an auto_increment or serial type. Returns undef if the
2106 driver does not support the method or can't determine the value.
2107
2108 The $catalog, $schema, $table, and $field parameters may be required
2109 for some drivers (see below). If you don't know the parameter values
2110 and your driver does not need them, then use "undef" for each.
2111
2112 There are several caveats to be aware of with this method if you want
2113 to use it for portable applications:
2114
2115 * For some drivers the value may only available immediately after the
2116 insert statement has executed (e.g., mysql, Informix).
2117
2118 * For some drivers the $catalog, $schema, $table, and $field parameters
2119 are required, for others they are ignored (e.g., mysql).
2120
2121 * Drivers may return an indeterminate value if no insert has been
2122 performed yet.
2123
2124 * For some drivers the value may only be available if placeholders have
2125 not been used (e.g., Sybase, MS SQL). In this case the value returned
2126 would be from the last non-placeholder insert statement.
2127
2128 * Some drivers may need driver-specific hints about how to get the
2129 value. For example, being told the name of the database 'sequence'
2130 object that holds the value. Any such hints are passed as driver-
2131 specific attributes in the \%attr parameter.
2132
2133 * If the underlying database offers nothing better, then some drivers
2134 may attempt to implement this method by executing ""select max($field)
2135 from $table"". Drivers using any approach like this should issue a
2136 warning if "AutoCommit" is true because it is generally unsafe -
2137 another process may have modified the table between your insert and the
2138 select. For situations where you know it is safe, such as when you have
2139 locked the table, you can silence the warning by passing "Warn" => 0 in
2140 \%attr.
2141
2142 * If no insert has been performed yet, or the last insert failed, then
2143 the value is implementation defined.
2144
2145 Given all the caveats above, it's clear that this method must be used
2146 with care.
2147
2148 The "last_insert_id" method was added in DBI 1.38.
2149
2150 "selectrow_array"
2151
2152 @row_ary = $dbh->selectrow_array($statement);
2153 @row_ary = $dbh->selectrow_array($statement, \%attr);
2154 @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
2155
2156 This utility method combines "prepare", "execute" and "fetchrow_array"
2157 into a single call. If called in a list context, it returns the first
2158 row of data from the statement. The $statement parameter can be a
2159 previously prepared statement handle, in which case the "prepare" is
2160 skipped.
2161
2162 If any method fails, and "RaiseError" is not set, "selectrow_array"
2163 will return an empty list.
2164
2165 If called in a scalar context for a statement handle that has more than
2166 one column, it is undefined whether the driver will return the value of
2167 the first column or the last. So don't do that. Also, in a scalar
2168 context, an "undef" is returned if there are no more rows or if an
2169 error occurred. That "undef" can't be distinguished from an "undef"
2170 returned because the first field value was NULL. For these reasons you
2171 should exercise some caution if you use "selectrow_array" in a scalar
2172 context, or just don't do that.
2173
2174 "selectrow_arrayref"
2175
2176 $ary_ref = $dbh->selectrow_arrayref($statement);
2177 $ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
2178 $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
2179
2180 This utility method combines "prepare", "execute" and
2181 "fetchrow_arrayref" into a single call. It returns the first row of
2182 data from the statement. The $statement parameter can be a previously
2183 prepared statement handle, in which case the "prepare" is skipped.
2184
2185 If any method fails, and "RaiseError" is not set, "selectrow_array"
2186 will return undef.
2187
2188 "selectrow_hashref"
2189
2190 $hash_ref = $dbh->selectrow_hashref($statement);
2191 $hash_ref = $dbh->selectrow_hashref($statement, \%attr);
2192 $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
2193
2194 This utility method combines "prepare", "execute" and
2195 "fetchrow_hashref" into a single call. It returns the first row of data
2196 from the statement. The $statement parameter can be a previously
2197 prepared statement handle, in which case the "prepare" is skipped.
2198
2199 If any method fails, and "RaiseError" is not set, "selectrow_hashref"
2200 will return undef.
2201
2202 "selectall_arrayref"
2203
2204 $ary_ref = $dbh->selectall_arrayref($statement);
2205 $ary_ref = $dbh->selectall_arrayref($statement, \%attr);
2206 $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
2207
2208 This utility method combines "prepare", "execute" and
2209 "fetchall_arrayref" into a single call. It returns a reference to an
2210 array containing a reference to an array (or hash, see below) for each
2211 row of data fetched.
2212
2213 The $statement parameter can be a previously prepared statement handle,
2214 in which case the "prepare" is skipped. This is recommended if the
2215 statement is going to be executed many times.
2216
2217 If "RaiseError" is not set and any method except "fetchall_arrayref"
2218 fails then "selectall_arrayref" will return "undef"; if
2219 "fetchall_arrayref" fails then it will return with whatever data has
2220 been fetched thus far. You should check "$sth->err" afterwards (or use
2221 the "RaiseError" attribute) to discover if the data is complete or was
2222 truncated due to an error.
2223
2224 The "fetchall_arrayref" method called by "selectall_arrayref" supports
2225 a $max_rows parameter. You can specify a value for $max_rows by
2226 including a '"MaxRows"' attribute in \%attr. In which case finish() is
2227 called for you after fetchall_arrayref() returns.
2228
2229 The "fetchall_arrayref" method called by "selectall_arrayref" also
2230 supports a $slice parameter. You can specify a value for $slice by
2231 including a '"Slice"' or '"Columns"' attribute in \%attr. The only
2232 difference between the two is that if "Slice" is not defined and
2233 "Columns" is an array ref, then the array is assumed to contain column
2234 index values (which count from 1), rather than perl array index values.
2235 In which case the array is copied and each value decremented before
2236 passing to "/fetchall_arrayref".
2237
2238 You may often want to fetch an array of rows where each row is stored
2239 as a hash. That can be done simple using:
2240
2241 my $emps = $dbh->selectall_arrayref(
2242 "SELECT ename FROM emp ORDER BY ename",
2243 { Slice => {} }
2244 );
2245 foreach my $emp ( @$emps ) {
2246 print "Employee: $emp->{ename}\n";
2247 }
2248
2249 Or, to fetch into an array instead of an array ref:
2250
2251 @result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) };
2252
2253 See "fetchall_arrayref" method for more details.
2254
2255 "selectall_hashref"
2256
2257 $hash_ref = $dbh->selectall_hashref($statement, $key_field);
2258 $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr);
2259 $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values);
2260
2261 This utility method combines "prepare", "execute" and
2262 "fetchall_hashref" into a single call. It returns a reference to a hash
2263 containing one entry, at most, for each row, as returned by
2264 fetchall_hashref().
2265
2266 The $statement parameter can be a previously prepared statement handle,
2267 in which case the "prepare" is skipped. This is recommended if the
2268 statement is going to be executed many times.
2269
2270 The $key_field parameter defines which column, or columns, are used as
2271 keys in the returned hash. It can either be the name of a single field,
2272 or a reference to an array containing multiple field names. Using
2273 multiple names yields a tree of nested hashes.
2274
2275 If a row has the same key as an earlier row then it replaces the
2276 earlier row.
2277
2278 If any method except "fetchrow_hashref" fails, and "RaiseError" is not
2279 set, "selectall_hashref" will return "undef". If "fetchrow_hashref"
2280 fails and "RaiseError" is not set, then it will return with whatever
2281 data it has fetched thus far. $DBI::err should be checked to catch
2282 that.
2283
2284 See fetchall_hashref() for more details.
2285
2286 "selectcol_arrayref"
2287
2288 $ary_ref = $dbh->selectcol_arrayref($statement);
2289 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
2290 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
2291
2292 This utility method combines "prepare", "execute", and fetching one
2293 column from all the rows, into a single call. It returns a reference to
2294 an array containing the values of the first column from each row.
2295
2296 The $statement parameter can be a previously prepared statement handle,
2297 in which case the "prepare" is skipped. This is recommended if the
2298 statement is going to be executed many times.
2299
2300 If any method except "fetch" fails, and "RaiseError" is not set,
2301 "selectcol_arrayref" will return "undef". If "fetch" fails and
2302 "RaiseError" is not set, then it will return with whatever data it has
2303 fetched thus far. $DBI::err should be checked to catch that.
2304
2305 The "selectcol_arrayref" method defaults to pushing a single column
2306 value (the first) from each row into the result array. However, it can
2307 also push another column, or even multiple columns per row, into the
2308 result array. This behaviour can be specified via a '"Columns"'
2309 attribute which must be a ref to an array containing the column number
2310 or numbers to use. For example:
2311
2312 # get array of id and name pairs:
2313 my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] });
2314 my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name
2315
2316 You can specify a maximum number of rows to fetch by including a
2317 '"MaxRows"' attribute in \%attr.
2318
2319 "prepare"
2320
2321 $sth = $dbh->prepare($statement) or die $dbh->errstr;
2322 $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr;
2323
2324 Prepares a statement for later execution by the database engine and
2325 returns a reference to a statement handle object.
2326
2327 The returned statement handle can be used to get attributes of the
2328 statement and invoke the "execute" method. See "Statement Handle
2329 Methods".
2330
2331 Drivers for engines without the concept of preparing a statement will
2332 typically just store the statement in the returned handle and process
2333 it when "$sth->execute" is called. Such drivers are unlikely to give
2334 much useful information about the statement, such as
2335 "$sth->{NUM_OF_FIELDS}", until after "$sth->execute" has been called.
2336 Portable applications should take this into account.
2337
2338 In general, DBI drivers do not parse the contents of the statement
2339 (other than simply counting any "Placeholders"). The statement is
2340 passed directly to the database engine, sometimes known as pass-thru
2341 mode. This has advantages and disadvantages. On the plus side, you can
2342 access all the functionality of the engine being used. On the downside,
2343 you're limited if you're using a simple engine, and you need to take
2344 extra care if writing applications intended to be portable between
2345 engines.
2346
2347 Portable applications should not assume that a new statement can be
2348 prepared and/or executed while still fetching results from a previous
2349 statement.
2350
2351 Some command-line SQL tools use statement terminators, like a
2352 semicolon, to indicate the end of a statement. Such terminators should
2353 not normally be used with the DBI.
2354
2355 "prepare_cached"
2356
2357 $sth = $dbh->prepare_cached($statement)
2358 $sth = $dbh->prepare_cached($statement, \%attr)
2359 $sth = $dbh->prepare_cached($statement, \%attr, $if_active)
2360
2361 Like "prepare" except that the statement handle returned will be stored
2362 in a hash associated with the $dbh. If another call is made to
2363 "prepare_cached" with the same $statement and %attr parameter values,
2364 then the corresponding cached $sth will be returned without contacting
2365 the database server.
2366
2367 The $if_active parameter lets you adjust the behaviour if an already
2368 cached statement handle is still Active. There are several
2369 alternatives:
2370
2371 0: A warning will be generated, and finish() will be called on the
2372 statement handle before it is returned. This is the default behaviour
2373 if $if_active is not passed.
2374 1: finish() will be called on the statement handle, but the warning is
2375 suppressed.
2376 2: Disables any checking.
2377 3: The existing active statement handle will be removed from the cache
2378 and a new statement handle prepared and cached in its place. This is
2379 the safest option because it doesn't affect the state of the old
2380 handle, it just removes it from the cache. [Added in DBI 1.40]
2381
2382 Here are some examples of "prepare_cached":
2383
2384 sub insert_hash {
2385 my ($table, $field_values) = @_;
2386 # sort to keep field order, and thus sql, stable for prepare_cached
2387 my @fields = sort keys %$field_values;
2388 my @values = @{$field_values}{@fields};
2389 my $sql = sprintf "insert into %s (%s) values (%s)",
2390 $table, join(",", @fields), join(",", ("?")x@fields);
2391 my $sth = $dbh->prepare_cached($sql);
2392 return $sth->execute(@values);
2393 }
2394
2395 sub search_hash {
2396 my ($table, $field_values) = @_;
2397 # sort to keep field order, and thus sql, stable for prepare_cached
2398 my @fields = sort keys %$field_values;
2399 my @values = @{$field_values}{@fields};
2400 my $qualifier = "";
2401 $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields;
2402 $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier");
2403 return $dbh->selectall_arrayref($sth, {}, @values);
2404 }
2405
2406 Caveat emptor: This caching can be useful in some applications, but it
2407 can also cause problems and should be used with care. Here is a
2408 contrived case where caching would cause a significant problem:
2409
2410 my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
2411 $sth->execute(...);
2412 while (my $data = $sth->fetchrow_hashref) {
2413
2414 # later, in some other code called within the loop...
2415 my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
2416 $sth2->execute(...);
2417 while (my $data2 = $sth2->fetchrow_arrayref) {
2418 do_stuff(...);
2419 }
2420 }
2421
2422 In this example, since both handles are preparing the exact same
2423 statement, $sth2 will not be its own statement handle, but a duplicate
2424 of $sth returned from the cache. The results will certainly not be what
2425 you expect. Typically the the inner fetch loop will work normally,
2426 fetching all the records and terminating when there are no more, but
2427 now $sth is the same as $sth2 the outer fetch loop will also terminate.
2428
2429 You'll know if you run into this problem because prepare_cached() will
2430 generate a warning by default (when $if_active is false).
2431
2432 The cache used by prepare_cached() is keyed by both the statement and
2433 any attributes so you can also avoid this issue by doing something
2434 like:
2435
2436 $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ });
2437
2438 which will ensure that prepare_cached only returns statements cached by
2439 that line of code in that source file.
2440
2441 If you'd like the cache to managed intelligently, you can tie the
2442 hashref returned by "CachedKids" to an appropriate caching module, such
2443 as Tie::Cache::LRU:
2444
2445 my $cache;
2446 tie %$cache, 'Tie::Cache::LRU', 500;
2447 $dbh->{CachedKids} = $cache;
2448
2449 "commit"
2450
2451 $rc = $dbh->commit or die $dbh->errstr;
2452
2453 Commit (make permanent) the most recent series of database changes if
2454 the database supports transactions and AutoCommit is off.
2455
2456 If "AutoCommit" is on, then calling "commit" will issue a "commit
2457 ineffective with AutoCommit" warning.
2458
2459 See also "Transactions" in the "FURTHER INFORMATION" section below.
2460
2461 "rollback"
2462
2463 $rc = $dbh->rollback or die $dbh->errstr;
2464
2465 Rollback (undo) the most recent series of uncommitted database changes
2466 if the database supports transactions and AutoCommit is off.
2467
2468 If "AutoCommit" is on, then calling "rollback" will issue a "rollback
2469 ineffective with AutoCommit" warning.
2470
2471 See also "Transactions" in the "FURTHER INFORMATION" section below.
2472
2473 "begin_work"
2474
2475 $rc = $dbh->begin_work or die $dbh->errstr;
2476
2477 Enable transactions (by turning "AutoCommit" off) until the next call
2478 to "commit" or "rollback". After the next "commit" or "rollback",
2479 "AutoCommit" will automatically be turned on again.
2480
2481 If "AutoCommit" is already off when "begin_work" is called then it does
2482 nothing except return an error. If the driver does not support
2483 transactions then when "begin_work" attempts to set "AutoCommit" off
2484 the driver will trigger a fatal error.
2485
2486 See also "Transactions" in the "FURTHER INFORMATION" section below.
2487
2488 "disconnect"
2489
2490 $rc = $dbh->disconnect or warn $dbh->errstr;
2491
2492 Disconnects the database from the database handle. "disconnect" is
2493 typically only used before exiting the program. The handle is of little
2494 use after disconnecting.
2495
2496 The transaction behaviour of the "disconnect" method is, sadly,
2497 undefined. Some database systems (such as Oracle and Ingres) will
2498 automatically commit any outstanding changes, but others (such as
2499 Informix) will rollback any outstanding changes. Applications not
2500 using "AutoCommit" should explicitly call "commit" or "rollback" before
2501 calling "disconnect".
2502
2503 The database is automatically disconnected by the "DESTROY" method if
2504 still connected when there are no longer any references to the handle.
2505 The "DESTROY" method for each driver should implicitly call "rollback"
2506 to undo any uncommitted changes. This is vital behaviour to ensure that
2507 incomplete transactions don't get committed simply because Perl calls
2508 "DESTROY" on every object before exiting. Also, do not rely on the
2509 order of object destruction during "global destruction", as it is
2510 undefined.
2511
2512 Generally, if you want your changes to be committed or rolled back when
2513 you disconnect, then you should explicitly call "commit" or "rollback"
2514 before disconnecting.
2515
2516 If you disconnect from a database while you still have active statement
2517 handles (e.g., SELECT statement handles that may have more data to
2518 fetch), you will get a warning. The warning may indicate that a fetch
2519 loop terminated early, perhaps due to an uncaught error. To avoid the
2520 warning call the "finish" method on the active handles.
2521
2522 "ping"
2523
2524 $rc = $dbh->ping;
2525
2526 Attempts to determine, in a reasonably efficient way, if the database
2527 server is still running and the connection to it is still working.
2528 Individual drivers should implement this function in the most suitable
2529 manner for their database engine.
2530
2531 The current default implementation always returns true without actually
2532 doing anything. Actually, it returns ""0 but true"" which is true but
2533 zero. That way you can tell if the return value is genuine or just the
2534 default. Drivers should override this method with one that does the
2535 right thing for their type of database.
2536
2537 Few applications would have direct use for this method. See the
2538 specialized Apache::DBI module for one example usage.
2539
2540 "get_info"
2541
2542 $value = $dbh->get_info( $info_type );
2543
2544 Returns information about the implementation, i.e. driver and data
2545 source capabilities, restrictions etc. It returns "undef" for unknown
2546 or unimplemented information types. For example:
2547
2548 $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER
2549 $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT
2550
2551 See "Standards Reference Information" for more detailed information
2552 about the information types and their meanings and possible return
2553 values.
2554
2555 The DBI::Const::GetInfoType module exports a %GetInfoType hash that can
2556 be used to map info type names to numbers. For example:
2557
2558 $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );
2559
2560 The names are a merging of the ANSI and ODBC standards (which differ in
2561 some cases). See DBI::Const::GetInfoType for more details.
2562
2563 Because some DBI methods make use of get_info(), drivers are strongly
2564 encouraged to support at least the following very minimal set of
2565 information types to ensure the DBI itself works properly:
2566
2567 Type Name Example A Example B
2568 ---- -------------------------- ------------ ----------------
2569 17 SQL_DBMS_NAME 'ACCESS' 'Oracle'
2570 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...'
2571 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"'
2572 41 SQL_CATALOG_NAME_SEPARATOR '.' '@'
2573 114 SQL_CATALOG_LOCATION 1 2
2574
2575 "table_info"
2576
2577 $sth = $dbh->table_info( $catalog, $schema, $table, $type );
2578 $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr );
2579
2580 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
2581
2582 Returns an active statement handle that can be used to fetch
2583 information about tables and views that exist in the database.
2584
2585 The arguments $catalog, $schema and $table may accept search patterns
2586 according to the database/driver, for example: $table = '%FOO%';
2587 Remember that the underscore character ('"_"') is a search pattern that
2588 means match any character, so 'FOO_%' is the same as 'FOO%' and
2589 'FOO_BAR%' will match names like 'FOO1BAR'.
2590
2591 The value of $type is a comma-separated list of one or more types of
2592 tables to be returned in the result set. Each value may optionally be
2593 quoted, e.g.:
2594
2595 $type = "TABLE";
2596 $type = "'TABLE','VIEW'";
2597
2598 In addition the following special cases may also be supported by some
2599 drivers:
2600
2601 · If the value of $catalog is '%' and $schema and $table name are
2602 empty strings, the result set contains a list of catalog names.
2603 For example:
2604
2605 $sth = $dbh->table_info('%', '', '');
2606
2607 · If the value of $schema is '%' and $catalog and $table are empty
2608 strings, the result set contains a list of schema names.
2609
2610 · If the value of $type is '%' and $catalog, $schema, and $table are
2611 all empty strings, the result set contains a list of table types.
2612
2613 If your driver doesn't support one or more of the selection filter
2614 parameters then you may get back more than you asked for and can do the
2615 filtering yourself.
2616
2617 This method can be expensive, and can return a large amount of data.
2618 (For example, small Oracle installation returns over 2000 rows.) So
2619 it's a good idea to use the filters to limit the data as much as
2620 possible.
2621
2622 The statement handle returned has at least the following fields in the
2623 order show below. Other fields, after these, may also be present.
2624
2625 TABLE_CAT: Table catalog identifier. This field is NULL ("undef") if
2626 not applicable to the data source, which is usually the case. This
2627 field is empty if not applicable to the table.
2628
2629 TABLE_SCHEM: The name of the schema containing the TABLE_NAME value.
2630 This field is NULL ("undef") if not applicable to data source, and
2631 empty if not applicable to the table.
2632
2633 TABLE_NAME: Name of the table (or view, synonym, etc).
2634
2635 TABLE_TYPE: One of the following: "TABLE", "VIEW", "SYSTEM TABLE",
2636 "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type
2637 identifier that is specific to the data source.
2638
2639 REMARKS: A description of the table. May be NULL ("undef").
2640
2641 Note that "table_info" might not return records for all tables.
2642 Applications can use any valid table regardless of whether it's
2643 returned by "table_info".
2644
2645 See also "tables", "Catalog Methods" and "Standards Reference
2646 Information".
2647
2648 "column_info"
2649
2650 $sth = $dbh->column_info( $catalog, $schema, $table, $column );
2651
2652 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
2653
2654 Returns an active statement handle that can be used to fetch
2655 information about columns in specified tables.
2656
2657 The arguments $schema, $table and $column may accept search patterns
2658 according to the database/driver, for example: $table = '%FOO%';
2659
2660 Note: The support for the selection criteria is driver specific. If the
2661 driver doesn't support one or more of them then you may get back more
2662 than you asked for and can do the filtering yourself.
2663
2664 If the arguments don't match any tables then you'll still get a
2665 statement handle, it'll just return no rows.
2666
2667 The statement handle returned has at least the following fields in the
2668 order shown below. Other fields, after these, may also be present.
2669
2670 TABLE_CAT: The catalog identifier. This field is NULL ("undef") if not
2671 applicable to the data source, which is often the case. This field is
2672 empty if not applicable to the table.
2673
2674 TABLE_SCHEM: The schema identifier. This field is NULL ("undef") if
2675 not applicable to the data source, and empty if not applicable to the
2676 table.
2677
2678 TABLE_NAME: The table identifier. Note: A driver may provide column
2679 metadata not only for base tables, but also for derived objects like
2680 SYNONYMS etc.
2681
2682 COLUMN_NAME: The column identifier.
2683
2684 DATA_TYPE: The concise data type code.
2685
2686 TYPE_NAME: A data source dependent data type name.
2687
2688 COLUMN_SIZE: The column size. This is the maximum length in characters
2689 for character data types, the number of digits or bits for numeric data
2690 types or the length in the representation of temporal types. See the
2691 relevant specifications for detailed information.
2692
2693 BUFFER_LENGTH: The length in bytes of transferred data.
2694
2695 DECIMAL_DIGITS: The total number of significant digits to the right of
2696 the decimal point.
2697
2698 NUM_PREC_RADIX: The radix for numeric precision. The value is 10 or 2
2699 for numeric data types and NULL ("undef") if not applicable.
2700
2701 NULLABLE: Indicates if a column can accept NULLs. The following values
2702 are defined:
2703
2704 SQL_NO_NULLS 0
2705 SQL_NULLABLE 1
2706 SQL_NULLABLE_UNKNOWN 2
2707
2708 REMARKS: A description of the column.
2709
2710 COLUMN_DEF: The default value of the column, in a format that can be
2711 used directly in an SQL statement.
2712
2713 Note that this may be an expression and not simply the text used for
2714 the default value in the original CREATE TABLE statement. For example,
2715 given:
2716
2717 col1 char(30) default current_user -- a 'function'
2718 col2 char(30) default 'string' -- a string literal
2719
2720 where "current_user" is the name of a function, the corresponding
2721 "COLUMN_DEF" values would be:
2722
2723 Database col1 col2
2724 -------- ---- ----
2725 Oracle: current_user 'string'
2726 Postgres: "current_user"() 'string'::text
2727 MS SQL: (user_name()) ('string')
2728
2729 SQL_DATA_TYPE: The SQL data type.
2730
2731 SQL_DATETIME_SUB: The subtype code for datetime and interval data
2732 types.
2733
2734 CHAR_OCTET_LENGTH: The maximum length in bytes of a character or binary
2735 data type column.
2736
2737 ORDINAL_POSITION: The column sequence number (starting with 1).
2738
2739 IS_NULLABLE: Indicates if the column can accept NULLs. Possible values
2740 are: 'NO', 'YES' and ''.
2741
2742 SQL/CLI defines the following additional columns:
2743
2744 CHAR_SET_CAT
2745 CHAR_SET_SCHEM
2746 CHAR_SET_NAME
2747 COLLATION_CAT
2748 COLLATION_SCHEM
2749 COLLATION_NAME
2750 UDT_CAT
2751 UDT_SCHEM
2752 UDT_NAME
2753 DOMAIN_CAT
2754 DOMAIN_SCHEM
2755 DOMAIN_NAME
2756 SCOPE_CAT
2757 SCOPE_SCHEM
2758 SCOPE_NAME
2759 MAX_CARDINALITY
2760 DTD_IDENTIFIER
2761 IS_SELF_REF
2762
2763 Drivers capable of supplying any of those values should do so in the
2764 corresponding column and supply undef values for the others.
2765
2766 Drivers wishing to provide extra database/driver specific information
2767 should do so in extra columns beyond all those listed above, and use
2768 lowercase field names with the driver-specific prefix (i.e.,
2769 'ora_...'). Applications accessing such fields should do so by name and
2770 not by column number.
2771
2772 The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME and
2773 ORDINAL_POSITION.
2774
2775 Note: There is some overlap with statement handle attributes (in perl)
2776 and SQLDescribeCol (in ODBC). However, SQLColumns provides more
2777 metadata.
2778
2779 See also "Catalog Methods" and "Standards Reference Information".
2780
2781 "primary_key_info"
2782
2783 $sth = $dbh->primary_key_info( $catalog, $schema, $table );
2784
2785 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
2786
2787 Returns an active statement handle that can be used to fetch
2788 information about columns that make up the primary key for a table.
2789 The arguments don't accept search patterns (unlike table_info()).
2790
2791 The statement handle will return one row per column, ordered by
2792 TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ. If there is no
2793 primary key then the statement handle will fetch no rows.
2794
2795 Note: The support for the selection criteria, such as $catalog, is
2796 driver specific. If the driver doesn't support catalogs and/or
2797 schemas, it may ignore these criteria.
2798
2799 The statement handle returned has at least the following fields in the
2800 order shown below. Other fields, after these, may also be present.
2801
2802 TABLE_CAT: The catalog identifier. This field is NULL ("undef") if not
2803 applicable to the data source, which is often the case. This field is
2804 empty if not applicable to the table.
2805
2806 TABLE_SCHEM: The schema identifier. This field is NULL ("undef") if
2807 not applicable to the data source, and empty if not applicable to the
2808 table.
2809
2810 TABLE_NAME: The table identifier.
2811
2812 COLUMN_NAME: The column identifier.
2813
2814 KEY_SEQ: The column sequence number (starting with 1). Note: This
2815 field is named ORDINAL_POSITION in SQL/CLI.
2816
2817 PK_NAME: The primary key constraint identifier. This field is NULL
2818 ("undef") if not applicable to the data source.
2819
2820 See also "Catalog Methods" and "Standards Reference Information".
2821
2822 "primary_key"
2823
2824 @key_column_names = $dbh->primary_key( $catalog, $schema, $table );
2825
2826 Simple interface to the primary_key_info() method. Returns a list of
2827 the column names that comprise the primary key of the specified table.
2828 The list is in primary key column sequence order. If there is no
2829 primary key then an empty list is returned.
2830
2831 "foreign_key_info"
2832
2833 $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
2834 , $fk_catalog, $fk_schema, $fk_table );
2835
2836 $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
2837 , $fk_catalog, $fk_schema, $fk_table
2838 , \%attr );
2839
2840 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
2841
2842 Returns an active statement handle that can be used to fetch
2843 information about foreign keys in and/or referencing the specified
2844 table(s). The arguments don't accept search patterns (unlike
2845 table_info()).
2846
2847 $pk_catalog, $pk_schema, $pk_table identify the primary (unique) key
2848 table (PKT).
2849
2850 $fk_catalog, $fk_schema, $fk_table identify the foreign key table
2851 (FKT).
2852
2853 If both PKT and FKT are given, the function returns the foreign key, if
2854 any, in table FKT that refers to the primary (unique) key of table PKT.
2855 (Note: In SQL/CLI, the result is implementation-defined.)
2856
2857 If only PKT is given, then the result set contains the primary key of
2858 that table and all foreign keys that refer to it.
2859
2860 If only FKT is given, then the result set contains all foreign keys in
2861 that table and the primary keys to which they refer. (Note: In
2862 SQL/CLI, the result includes unique keys too.)
2863
2864 For example:
2865
2866 $sth = $dbh->foreign_key_info( undef, $user, 'master');
2867 $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail');
2868 $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail');
2869
2870 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
2871
2872 Note: The support for the selection criteria, such as $catalog, is
2873 driver specific. If the driver doesn't support catalogs and/or
2874 schemas, it may ignore these criteria.
2875
2876 The statement handle returned has the following fields in the order
2877 shown below. Because ODBC never includes unique keys, they define
2878 different columns in the result set than SQL/CLI. SQL/CLI column names
2879 are shown in parentheses.
2880
2881 PKTABLE_CAT ( UK_TABLE_CAT ): The primary (unique) key table
2882 catalog identifier. This field is NULL ("undef") if not applicable to
2883 the data source, which is often the case. This field is empty if not
2884 applicable to the table.
2885
2886 PKTABLE_SCHEM ( UK_TABLE_SCHEM ): The primary (unique) key table
2887 schema identifier. This field is NULL ("undef") if not applicable to
2888 the data source, and empty if not applicable to the table.
2889
2890 PKTABLE_NAME ( UK_TABLE_NAME ): The primary (unique) key table
2891 identifier.
2892
2893 PKCOLUMN_NAME (UK_COLUMN_NAME ): The primary (unique) key column
2894 identifier.
2895
2896 FKTABLE_CAT ( FK_TABLE_CAT ): The foreign key table catalog
2897 identifier. This field is NULL ("undef") if not applicable to the data
2898 source, which is often the case. This field is empty if not applicable
2899 to the table.
2900
2901 FKTABLE_SCHEM ( FK_TABLE_SCHEM ): The foreign key table schema
2902 identifier. This field is NULL ("undef") if not applicable to the data
2903 source, and empty if not applicable to the table.
2904
2905 FKTABLE_NAME ( FK_TABLE_NAME ): The foreign key table identifier.
2906
2907 FKCOLUMN_NAME ( FK_COLUMN_NAME ): The foreign key column
2908 identifier.
2909
2910 KEY_SEQ ( ORDINAL_POSITION ): The column sequence number
2911 (starting with 1).
2912
2913 UPDATE_RULE ( UPDATE_RULE ): The referential action for the
2914 UPDATE rule. The following codes are defined:
2915
2916 CASCADE 0
2917 RESTRICT 1
2918 SET NULL 2
2919 NO ACTION 3
2920 SET DEFAULT 4
2921
2922 DELETE_RULE ( DELETE_RULE ): The referential action for the
2923 DELETE rule. The codes are the same as for UPDATE_RULE.
2924
2925 FK_NAME ( FK_NAME ): The foreign key name.
2926
2927 PK_NAME ( UK_NAME ): The primary (unique) key name.
2928
2929 DEFERRABILITY ( DEFERABILITY ): The deferrability of the foreign
2930 key constraint. The following codes are defined:
2931
2932 INITIALLY DEFERRED 5
2933 INITIALLY IMMEDIATE 6
2934 NOT DEFERRABLE 7
2935
2936 ( UNIQUE_OR_PRIMARY ): This column is necessary if a
2937 driver includes all candidate (i.e. primary and alternate) keys in the
2938 result set (as specified by SQL/CLI). The value of this column is
2939 UNIQUE if the foreign key references an alternate key and PRIMARY if
2940 the foreign key references a primary key, or it may be undefined if the
2941 driver doesn't have access to the information.
2942
2943 See also "Catalog Methods" and "Standards Reference Information".
2944
2945 "statistics_info"
2946
2947 Warning: This method is experimental and may change.
2948
2949 $sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick );
2950
2951 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
2952
2953 Returns an active statement handle that can be used to fetch
2954 statistical information about a table and its indexes.
2955
2956 The arguments don't accept search patterns (unlike "table_info").
2957
2958 If the boolean argument $unique_only is true, only UNIQUE indexes will
2959 be returned in the result set, otherwise all indexes will be returned.
2960
2961 If the boolean argument $quick is set, the actual statistical
2962 information columns (CARDINALITY and PAGES) will only be returned if
2963 they are readily available from the server, and might not be current.
2964 Some databases may return stale statistics or no statistics at all with
2965 this flag set.
2966
2967 The statement handle will return at most one row per column name per
2968 index, plus at most one row for the entire table itself, ordered by
2969 NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION.
2970
2971 Note: The support for the selection criteria, such as $catalog, is
2972 driver specific. If the driver doesn't support catalogs and/or
2973 schemas, it may ignore these criteria.
2974
2975 The statement handle returned has at least the following fields in the
2976 order shown below. Other fields, after these, may also be present.
2977
2978 TABLE_CAT: The catalog identifier. This field is NULL ("undef") if not
2979 applicable to the data source, which is often the case. This field is
2980 empty if not applicable to the table.
2981
2982 TABLE_SCHEM: The schema identifier. This field is NULL ("undef") if
2983 not applicable to the data source, and empty if not applicable to the
2984 table.
2985
2986 TABLE_NAME: The table identifier.
2987
2988 NON_UNIQUE: Unique index indicator. Returns 0 for unique indexes, 1
2989 for non-unique indexes
2990
2991 INDEX_QUALIFIER: Index qualifier identifier. The identifier that is
2992 used to qualify the index name when doing a "DROP INDEX"; NULL
2993 ("undef") is returned if an index qualifier is not supported by the
2994 data source. If a non-NULL (defined) value is returned in this column,
2995 it must be used to qualify the index name on a "DROP INDEX" statement;
2996 otherwise, the TABLE_SCHEM should be used to qualify the index name.
2997
2998 INDEX_NAME: The index identifier.
2999
3000 TYPE: The type of information being returned. Can be any of the
3001 following values: 'table', 'btree', 'clustered', 'content', 'hashed',
3002 or 'other'.
3003
3004 In the case that this field is 'table', all fields other than
3005 TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE, CARDINALITY, and PAGES will
3006 be NULL ("undef").
3007
3008 ORDINAL_POSITION: Column sequence number (starting with 1).
3009
3010 COLUMN_NAME: The column identifier.
3011
3012 ASC_OR_DESC: Column sort sequence. "A" for Ascending, "D" for
3013 Descending, or NULL ("undef") if not supported for this index.
3014
3015 CARDINALITY: Cardinality of the table or index. For indexes, this is
3016 the number of unique values in the index. For tables, this is the
3017 number of rows in the table. If not supported, the value will be NULL
3018 ("undef").
3019
3020 PAGES: Number of storage pages used by this table or index. If not
3021 supported, the value will be NULL ("undef").
3022
3023 FILTER_CONDITION: The index filter condition as a string. If the index
3024 is not a filtered index, or it cannot be determined whether the index
3025 is a filtered index, this value is NULL ("undef"). If the index is a
3026 filtered index, but the filter condition cannot be determined, this
3027 value is the empty string ''. Otherwise it will be the literal filter
3028 condition as a string, such as "SALARY <= 4500".
3029
3030 See also "Catalog Methods" and "Standards Reference Information".
3031
3032 "tables"
3033
3034 @names = $dbh->tables( $catalog, $schema, $table, $type );
3035 @names = $dbh->tables; # deprecated
3036
3037 Simple interface to table_info(). Returns a list of matching table
3038 names, possibly including a catalog/schema prefix.
3039
3040 See "table_info" for a description of the parameters.
3041
3042 If "$dbh->get_info(29)" returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR)
3043 then the table names are constructed and quoted by "quote_identifier"
3044 to ensure they are usable even if they contain whitespace or reserved
3045 words etc. This means that the table names returned will include quote
3046 characters.
3047
3048 "type_info_all"
3049
3050 $type_info_all = $dbh->type_info_all;
3051
3052 Returns a reference to an array which holds information about each data
3053 type variant supported by the database and driver. The array and its
3054 contents should be treated as read-only.
3055
3056 The first item is a reference to an 'index' hash of "Name ="> "Index"
3057 pairs. The items following that are references to arrays, one per
3058 supported data type variant. The leading index hash defines the names
3059 and order of the fields within the arrays that follow it. For example:
3060
3061 $type_info_all = [
3062 { TYPE_NAME => 0,
3063 DATA_TYPE => 1,
3064 COLUMN_SIZE => 2, # was PRECISION originally
3065 LITERAL_PREFIX => 3,
3066 LITERAL_SUFFIX => 4,
3067 CREATE_PARAMS => 5,
3068 NULLABLE => 6,
3069 CASE_SENSITIVE => 7,
3070 SEARCHABLE => 8,
3071 UNSIGNED_ATTRIBUTE=> 9,
3072 FIXED_PREC_SCALE => 10, # was MONEY originally
3073 AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
3074 LOCAL_TYPE_NAME => 12,
3075 MINIMUM_SCALE => 13,
3076 MAXIMUM_SCALE => 14,
3077 SQL_DATA_TYPE => 15,
3078 SQL_DATETIME_SUB => 16,
3079 NUM_PREC_RADIX => 17,
3080 INTERVAL_PRECISION=> 18,
3081 },
3082 [ 'VARCHAR', SQL_VARCHAR,
3083 undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
3084 ],
3085 [ 'INTEGER', SQL_INTEGER,
3086 undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
3087 ],
3088 ];
3089
3090 More than one row may have the same value in the "DATA_TYPE" field if
3091 there are different ways to spell the type name and/or there are
3092 variants of the type with different attributes (e.g., with and without
3093 "AUTO_UNIQUE_VALUE" set, with and without "UNSIGNED_ATTRIBUTE", etc).
3094
3095 The rows are ordered by "DATA_TYPE" first and then by how closely each
3096 type maps to the corresponding ODBC SQL data type, closest first.
3097
3098 The meaning of the fields is described in the documentation for the
3099 "type_info" method.
3100
3101 An 'index' hash is provided so you don't need to rely on index values
3102 defined above. However, using DBD::ODBC with some old ODBC drivers may
3103 return older names, shown as comments in the example above. Another
3104 issue with the index hash is that the lettercase of the keys is not
3105 defined. It is usually uppercase, as show here, but drivers may return
3106 names with any lettercase.
3107
3108 Drivers are also free to return extra driver-specific columns of
3109 information - though it's recommended that they start at column index
3110 50 to leave room for expansion of the DBI/ODBC specification.
3111
3112 The type_info_all() method is not normally used directly. The
3113 "type_info" method provides a more usable and useful interface to the
3114 data.
3115
3116 "type_info"
3117
3118 @type_info = $dbh->type_info($data_type);
3119
3120 Returns a list of hash references holding information about one or more
3121 variants of $data_type. The list is ordered by "DATA_TYPE" first and
3122 then by how closely each type maps to the corresponding ODBC SQL data
3123 type, closest first. If called in a scalar context then only the first
3124 (best) element is returned.
3125
3126 If $data_type is undefined or "SQL_ALL_TYPES", then the list will
3127 contain hashes for all data type variants supported by the database and
3128 driver.
3129
3130 If $data_type is an array reference then "type_info" returns the
3131 information for the first type in the array that has any matches.
3132
3133 The keys of the hash follow the same letter case conventions as the
3134 rest of the DBI (see "Naming Conventions and Name Space"). The
3135 following uppercase items should always exist, though may be undef:
3136
3137 TYPE_NAME (string)
3138 Data type name for use in CREATE TABLE statements etc.
3139
3140 DATA_TYPE (integer)
3141 SQL data type number.
3142
3143 COLUMN_SIZE (integer)
3144 For numeric types, this is either the total number of digits (if
3145 the NUM_PREC_RADIX value is 10) or the total number of bits allowed
3146 in the column (if NUM_PREC_RADIX is 2).
3147
3148 For string types, this is the maximum size of the string in
3149 characters.
3150
3151 For date and interval types, this is the maximum number of
3152 characters needed to display the value.
3153
3154 LITERAL_PREFIX (string)
3155 Characters used to prefix a literal. A typical prefix is ""'"" for
3156 characters, or possibly ""0x"" for binary values passed as
3157 hexadecimal. NULL ("undef") is returned for data types for which
3158 this is not applicable.
3159
3160 LITERAL_SUFFIX (string)
3161 Characters used to suffix a literal. Typically ""'"" for
3162 characters. NULL ("undef") is returned for data types where this
3163 is not applicable.
3164
3165 CREATE_PARAMS (string)
3166 Parameter names for data type definition. For example,
3167 "CREATE_PARAMS" for a "DECIMAL" would be ""precision,scale"" if the
3168 DECIMAL type should be declared as "DECIMAL("precision,scale")"
3169 where precision and scale are integer values. For a "VARCHAR" it
3170 would be ""max length"". NULL ("undef") is returned for data types
3171 for which this is not applicable.
3172
3173 NULLABLE (integer)
3174 Indicates whether the data type accepts a NULL value: 0 or an empty
3175 string = no, 1 = yes, 2 = unknown.
3176
3177 CASE_SENSITIVE (boolean)
3178 Indicates whether the data type is case sensitive in collations and
3179 comparisons.
3180
3181 SEARCHABLE (integer)
3182 Indicates how the data type can be used in a WHERE clause, as
3183 follows:
3184
3185 0 - Cannot be used in a WHERE clause
3186 1 - Only with a LIKE predicate
3187 2 - All comparison operators except LIKE
3188 3 - Can be used in a WHERE clause with any comparison operator
3189
3190 UNSIGNED_ATTRIBUTE (boolean)
3191 Indicates whether the data type is unsigned. NULL ("undef") is
3192 returned for data types for which this is not applicable.
3193
3194 FIXED_PREC_SCALE (boolean)
3195 Indicates whether the data type always has the same precision and
3196 scale (such as a money type). NULL ("undef") is returned for data
3197 types for which this is not applicable.
3198
3199 AUTO_UNIQUE_VALUE (boolean)
3200 Indicates whether a column of this data type is automatically set
3201 to a unique value whenever a new row is inserted. NULL ("undef")
3202 is returned for data types for which this is not applicable.
3203
3204 LOCAL_TYPE_NAME (string)
3205 Localized version of the "TYPE_NAME" for use in dialog with users.
3206 NULL ("undef") is returned if a localized name is not available (in
3207 which case "TYPE_NAME" should be used).
3208
3209 MINIMUM_SCALE (integer)
3210 The minimum scale of the data type. If a data type has a fixed
3211 scale, then "MAXIMUM_SCALE" holds the same value. NULL ("undef")
3212 is returned for data types for which this is not applicable.
3213
3214 MAXIMUM_SCALE (integer)
3215 The maximum scale of the data type. If a data type has a fixed
3216 scale, then "MINIMUM_SCALE" holds the same value. NULL ("undef")
3217 is returned for data types for which this is not applicable.
3218
3219 SQL_DATA_TYPE (integer)
3220 This column is the same as the "DATA_TYPE" column, except for
3221 interval and datetime data types. For interval and datetime data
3222 types, the "SQL_DATA_TYPE" field will return "SQL_INTERVAL" or
3223 "SQL_DATETIME", and the "SQL_DATETIME_SUB" field below will return
3224 the subcode for the specific interval or datetime data type. If
3225 this field is NULL, then the driver does not support or report on
3226 interval or datetime subtypes.
3227
3228 SQL_DATETIME_SUB (integer)
3229 For interval or datetime data types, where the "SQL_DATA_TYPE"
3230 field above is "SQL_INTERVAL" or "SQL_DATETIME", this field will
3231 hold the subcode for the specific interval or datetime data type.
3232 Otherwise it will be NULL ("undef").
3233
3234 Although not mentioned explicitly in the standards, it seems there
3235 is a simple relationship between these values:
3236
3237 DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB
3238
3239 NUM_PREC_RADIX (integer)
3240 The radix value of the data type. For approximate numeric types,
3241 "NUM_PREC_RADIX" contains the value 2 and "COLUMN_SIZE" holds the
3242 number of bits. For exact numeric types, "NUM_PREC_RADIX" contains
3243 the value 10 and "COLUMN_SIZE" holds the number of decimal digits.
3244 NULL ("undef") is returned either for data types for which this is
3245 not applicable or if the driver cannot report this information.
3246
3247 INTERVAL_PRECISION (integer)
3248 The interval leading precision for interval types. NULL is returned
3249 either for data types for which this is not applicable or if the
3250 driver cannot report this information.
3251
3252 For example, to find the type name for the fields in a select statement
3253 you can do:
3254
3255 @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
3256
3257 Since DBI and ODBC drivers vary in how they map their types into the
3258 ISO standard types you may need to search for more than one type.
3259 Here's an example looking for a usable type to store a date:
3260
3261 $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
3262
3263 Similarly, to more reliably find a type to store small integers, you
3264 could use a list starting with "SQL_SMALLINT", "SQL_INTEGER",
3265 "SQL_DECIMAL", etc.
3266
3267 See also "Standards Reference Information".
3268
3269 "quote"
3270
3271 $sql = $dbh->quote($value);
3272 $sql = $dbh->quote($value, $data_type);
3273
3274 Quote a string literal for use as a literal value in an SQL statement,
3275 by escaping any special characters (such as quotation marks) contained
3276 within the string and adding the required type of outer quotation
3277 marks.
3278
3279 $sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
3280 $dbh->quote("Don't");
3281
3282 For most database types, at least those that conform to SQL standards,
3283 quote would return 'Don''t' (including the outer quotation marks). For
3284 others it may return something like 'Don\'t'
3285
3286 An undefined $value value will be returned as the string "NULL"
3287 (without single quotation marks) to match how NULLs are represented in
3288 SQL.
3289
3290 If $data_type is supplied, it is used to try to determine the required
3291 quoting behaviour by using the information returned by "type_info". As
3292 a special case, the standard numeric types are optimized to return
3293 $value without calling "type_info".
3294
3295 Quote will probably not be able to deal with all possible input (such
3296 as binary data or data containing newlines), and is not related in any
3297 way with escaping or quoting shell meta-characters.
3298
3299 It is valid for the quote() method to return an SQL expression that
3300 evaluates to the desired string. For example:
3301
3302 $quoted = $dbh->quote("one\ntwo\0three")
3303
3304 may return something like:
3305
3306 CONCAT('one', CHAR(12), 'two', CHAR(0), 'three')
3307
3308 The quote() method should not be used with "Placeholders and Bind
3309 Values".
3310
3311 "quote_identifier"
3312
3313 $sql = $dbh->quote_identifier( $name );
3314 $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr );
3315
3316 Quote an identifier (table name etc.) for use in an SQL statement, by
3317 escaping any special characters (such as double quotation marks) it
3318 contains and adding the required type of outer quotation marks.
3319
3320 Undefined names are ignored and the remainder are quoted and then
3321 joined together, typically with a dot (".") character. For example:
3322
3323 $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' );
3324
3325 would, for most database types, return "Her schema"."My table"
3326 (including all the double quotation marks).
3327
3328 If three names are supplied then the first is assumed to be a catalog
3329 name and special rules may be applied based on what "get_info" returns
3330 for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114).
3331 For example, for Oracle:
3332
3333 $id = $dbh->quote_identifier( 'link', 'schema', 'table' );
3334
3335 would return "schema"."table"@"link".
3336
3337 "take_imp_data"
3338
3339 $imp_data = $dbh->take_imp_data;
3340
3341 Leaves the $dbh in an almost dead, zombie-like, state and returns a
3342 binary string of raw implementation data from the driver which
3343 describes the current database connection. Effectively it detaches the
3344 underlying database API connection data from the DBI handle. After
3345 calling take_imp_data(), all other methods except "DESTROY" will
3346 generate a warning and return undef.
3347
3348 Why would you want to do this? You don't, forget I even mentioned it.
3349 Unless, that is, you're implementing something advanced like a multi-
3350 threaded connection pool. See DBI::Pool.
3351
3352 The returned $imp_data can be passed as a "dbi_imp_data" attribute to a
3353 later connect() call, even in a separate thread in the same process,
3354 where the driver can use it to 'adopt' the existing connection that the
3355 implementation data was taken from.
3356
3357 Some things to keep in mind...
3358
3359 * the $imp_data holds the only reference to the underlying database API
3360 connection data. That connection is still 'live' and won't be cleaned
3361 up properly unless the $imp_data is used to create a new $dbh which is
3362 then allowed to disconnect() normally.
3363
3364 * using the same $imp_data to create more than one other new $dbh at a
3365 time may well lead to unpleasant problems. Don't do that.
3366
3367 Any child statement handles are effectively destroyed when
3368 take_imp_data() is called.
3369
3370 The "take_imp_data" method was added in DBI 1.36 but wasn't useful till
3371 1.49.
3372
3373 Database Handle Attributes
3374 This section describes attributes specific to database handles.
3375
3376 Changes to these database handle attributes do not affect any other
3377 existing or future database handles.
3378
3379 Attempting to set or get the value of an unknown attribute generates a
3380 warning, except for private driver-specific attributes (which all have
3381 names starting with a lowercase letter).
3382
3383 Example:
3384
3385 $h->{AutoCommit} = ...; # set/write
3386 ... = $h->{AutoCommit}; # get/read
3387
3388 "AutoCommit" (boolean)
3389
3390 If true, then database changes cannot be rolled-back (undone). If
3391 false, then database changes automatically occur within a
3392 "transaction", which must either be committed or rolled back using the
3393 "commit" or "rollback" methods.
3394
3395 Drivers should always default to "AutoCommit" mode (an unfortunate
3396 choice largely forced on the DBI by ODBC and JDBC conventions.)
3397
3398 Attempting to set "AutoCommit" to an unsupported value is a fatal
3399 error. This is an important feature of the DBI. Applications that need
3400 full transaction behaviour can set "$dbh->{AutoCommit} = 0" (or set
3401 "AutoCommit" to 0 via "connect") without having to check that the value
3402 was assigned successfully.
3403
3404 For the purposes of this description, we can divide databases into
3405 three categories:
3406
3407 Databases which don't support transactions at all.
3408 Databases in which a transaction is always active.
3409 Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
3410
3411 * Databases which don't support transactions at all
3412
3413 For these databases, attempting to turn "AutoCommit" off is a fatal
3414 error. "commit" and "rollback" both issue warnings about being
3415 ineffective while "AutoCommit" is in effect.
3416
3417 * Databases in which a transaction is always active
3418
3419 These are typically mainstream commercial relational databases with
3420 "ANSI standard" transaction behaviour. If "AutoCommit" is off, then
3421 changes to the database won't have any lasting effect unless "commit"
3422 is called (but see also "disconnect"). If "rollback" is called then any
3423 changes since the last commit are undone.
3424
3425 If "AutoCommit" is on, then the effect is the same as if the DBI called
3426 "commit" automatically after every successful database operation. So
3427 calling "commit" or "rollback" explicitly while "AutoCommit" is on
3428 would be ineffective because the changes would have already been
3429 committed.
3430
3431 Changing "AutoCommit" from off to on will trigger a "commit".
3432
3433 For databases which don't support a specific auto-commit mode, the
3434 driver has to commit each statement automatically using an explicit
3435 "COMMIT" after it completes successfully (and roll it back using an
3436 explicit "ROLLBACK" if it fails). The error information reported to
3437 the application will correspond to the statement which was executed,
3438 unless it succeeded and the commit or rollback failed.
3439
3440 * Databases in which a transaction must be explicitly started
3441
3442 For these databases, the intention is to have them act like databases
3443 in which a transaction is always active (as described above).
3444
3445 To do this, the driver will automatically begin an explicit transaction
3446 when "AutoCommit" is turned off, or after a "commit" or "rollback" (or
3447 when the application issues the next database operation after one of
3448 those events).
3449
3450 In this way, the application does not have to treat these databases as
3451 a special case.
3452
3453 See "commit", "disconnect" and "Transactions" for other important notes
3454 about transactions.
3455
3456 "Driver" (handle)
3457
3458 Holds the handle of the parent driver. The only recommended use for
3459 this is to find the name of the driver using:
3460
3461 $dbh->{Driver}->{Name}
3462
3463 "Name" (string)
3464
3465 Holds the "name" of the database. Usually (and recommended to be) the
3466 same as the ""dbi:DriverName:..."" string used to connect to the
3467 database, but with the leading ""dbi:DriverName:"" removed.
3468
3469 "Statement" (string, read-only)
3470
3471 Returns the statement string passed to the most recent "prepare" method
3472 called in this database handle, even if that method failed. This is
3473 especially useful where "RaiseError" is enabled and the exception
3474 handler checks $@ and sees that a 'prepare' method call failed.
3475
3476 "RowCacheSize" (integer)
3477
3478 A hint to the driver indicating the size of the local row cache that
3479 the application would like the driver to use for future "SELECT"
3480 statements. If a row cache is not implemented, then setting
3481 "RowCacheSize" is ignored and getting the value returns "undef".
3482
3483 Some "RowCacheSize" values have special meaning, as follows:
3484
3485 0 - Automatically determine a reasonable cache size for each C<SELECT>
3486 1 - Disable the local row cache
3487 >1 - Cache this many rows
3488 <0 - Cache as many rows that will fit into this much memory for each C<SELECT>.
3489
3490 Note that large cache sizes may require a very large amount of memory
3491 (cached rows * maximum size of row). Also, a large cache will cause a
3492 longer delay not only for the first fetch, but also whenever the cache
3493 needs refilling.
3494
3495 See also the "RowsInCache" statement handle attribute.
3496
3497 "Username" (string)
3498
3499 Returns the username used to connect to the database.
3500
3502 This section lists the methods and attributes associated with DBI
3503 statement handles.
3504
3505 Statement Handle Methods
3506 The DBI defines the following methods for use on DBI statement handles:
3507
3508 "bind_param"
3509
3510 $sth->bind_param($p_num, $bind_value)
3511 $sth->bind_param($p_num, $bind_value, \%attr)
3512 $sth->bind_param($p_num, $bind_value, $bind_type)
3513
3514 The "bind_param" method takes a copy of $bind_value and associates it
3515 (binds it) with a placeholder, identified by $p_num, embedded in the
3516 prepared statement. Placeholders are indicated with question mark
3517 character ("?"). For example:
3518
3519 $dbh->{RaiseError} = 1; # save having to check each method call
3520 $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?");
3521 $sth->bind_param(1, "John%"); # placeholders are numbered from 1
3522 $sth->execute;
3523 DBI::dump_results($sth);
3524
3525 See "Placeholders and Bind Values" for more information.
3526
3527 Data Types for Placeholders
3528
3529 The "\%attr" parameter can be used to hint at the data type the
3530 placeholder should have. This is rarely needed. Typically, the driver
3531 is only interested in knowing if the placeholder should be bound as a
3532 number or a string.
3533
3534 $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
3535
3536 As a short-cut for the common case, the data type can be passed
3537 directly, in place of the "\%attr" hash reference. This example is
3538 equivalent to the one above:
3539
3540 $sth->bind_param(1, $value, SQL_INTEGER);
3541
3542 The "TYPE" value indicates the standard (non-driver-specific) type for
3543 this parameter. To specify the driver-specific type, the driver may
3544 support a driver-specific attribute, such as "{ ora_type => 97 }".
3545
3546 The SQL_INTEGER and other related constants can be imported using
3547
3548 use DBI qw(:sql_types);
3549
3550 See "DBI Constants" for more information.
3551
3552 The data type is 'sticky' in that bind values passed to execute() are
3553 bound with the data type specified by earlier bind_param() calls, if
3554 any. Portable applications should not rely on being able to change the
3555 data type after the first "bind_param" call.
3556
3557 Perl only has string and number scalar data types. All database types
3558 that aren't numbers are bound as strings and must be in a format the
3559 database will understand except where the bind_param() TYPE attribute
3560 specifies a type that implies a particular format. For example, given:
3561
3562 $sth->bind_param(1, $value, SQL_DATETIME);
3563
3564 the driver should expect $value to be in the ODBC standard SQL_DATETIME
3565 format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE,
3566 SQL_TIME etc.
3567
3568 As an alternative to specifying the data type in the "bind_param" call,
3569 you can let the driver pass the value as the default type ("VARCHAR").
3570 You can then use an SQL function to convert the type within the
3571 statement. For example:
3572
3573 INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
3574
3575 The "CONVERT" function used here is just an example. The actual
3576 function and syntax will vary between different databases and is non-
3577 portable.
3578
3579 See also "Placeholders and Bind Values" for more information.
3580
3581 "bind_param_inout"
3582
3583 $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr;
3584 $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ...
3585 $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ...
3586
3587 This method acts like "bind_param", but also enables values to be
3588 updated by the statement. The statement is typically a call to a stored
3589 procedure. The $bind_value must be passed as a reference to the actual
3590 value to be used.
3591
3592 Note that unlike "bind_param", the $bind_value variable is not copied
3593 when "bind_param_inout" is called. Instead, the value in the variable
3594 is read at the time "execute" is called.
3595
3596 The additional $max_len parameter specifies the minimum amount of
3597 memory to allocate to $bind_value for the new value. If the value
3598 returned from the database is too big to fit, then the execution should
3599 fail. If unsure what value to use, pick a generous length, i.e., a
3600 length larger than the longest value that would ever be returned. The
3601 only cost of using a larger value than needed is wasted memory.
3602
3603 Undefined values or "undef" are used to indicate null values. See also
3604 "Placeholders and Bind Values" for more information.
3605
3606 "bind_param_array"
3607
3608 $rc = $sth->bind_param_array($p_num, $array_ref_or_value)
3609 $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr)
3610 $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type)
3611
3612 The "bind_param_array" method is used to bind an array of values to a
3613 placeholder embedded in the prepared statement which is to be executed
3614 with "execute_array". For example:
3615
3616 $dbh->{RaiseError} = 1; # save having to check each method call
3617 $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)");
3618 $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]);
3619 $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]);
3620 $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row
3621 $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } );
3622
3623 The %attr ($bind_type) argument is the same as defined for
3624 "bind_param". Refer to "bind_param" for general details on using
3625 placeholders.
3626
3627 (Note that bind_param_array() can not be used to expand a placeholder
3628 into a list of values for a statement like "SELECT foo WHERE bar IN
3629 (?)". A placeholder can only ever represent one value per execution.)
3630
3631 Scalar values, including "undef", may also be bound by
3632 "bind_param_array". In which case the same value will be used for each
3633 "execute" call. Driver-specific implementations may behave differently,
3634 e.g., when binding to a stored procedure call, some databases may
3635 permit mixing scalars and arrays as arguments.
3636
3637 The default implementation provided by DBI (for drivers that have not
3638 implemented array binding) is to iteratively call "execute" for each
3639 parameter tuple provided in the bound arrays. Drivers may provide more
3640 optimized implementations using whatever bulk operation support the
3641 database API provides. The default driver behaviour should match the
3642 default DBI behaviour, but always consult your driver documentation as
3643 there may be driver specific issues to consider.
3644
3645 Note that the default implementation currently only supports non-data
3646 returning statements (INSERT, UPDATE, but not SELECT). Also,
3647 "bind_param_array" and "bind_param" cannot be mixed in the same
3648 statement execution, and "bind_param_array" must be used with
3649 "execute_array"; using "bind_param_array" will have no effect for
3650 "execute".
3651
3652 The "bind_param_array" method was added in DBI 1.22.
3653
3654 "execute"
3655
3656 $rv = $sth->execute or die $sth->errstr;
3657 $rv = $sth->execute(@bind_values) or die $sth->errstr;
3658
3659 Perform whatever processing is necessary to execute the prepared
3660 statement. An "undef" is returned if an error occurs. A successful
3661 "execute" always returns true regardless of the number of rows
3662 affected, even if it's zero (see below). It is always important to
3663 check the return status of "execute" (and most other DBI methods) for
3664 errors if you're not using "RaiseError".
3665
3666 For a non-"SELECT" statement, "execute" returns the number of rows
3667 affected, if known. If no rows were affected, then "execute" returns
3668 "0E0", which Perl will treat as 0 but will regard as true. Note that it
3669 is not an error for no rows to be affected by a statement. If the
3670 number of rows affected is not known, then "execute" returns -1.
3671
3672 For "SELECT" statements, execute simply "starts" the query within the
3673 database engine. Use one of the fetch methods to retrieve the data
3674 after calling "execute". The "execute" method does not return the
3675 number of rows that will be returned by the query (because most
3676 databases can't tell in advance), it simply returns a true value.
3677
3678 You can tell if the statement was a "SELECT" statement by checking if
3679 "$sth->{NUM_OF_FIELDS}" is greater than zero after calling "execute".
3680
3681 If any arguments are given, then "execute" will effectively call
3682 "bind_param" for each value before executing the statement. Values
3683 bound in this way are usually treated as "SQL_VARCHAR" types unless the
3684 driver can determine the correct type (which is rare), or unless
3685 "bind_param" (or "bind_param_inout") has already been used to specify
3686 the type.
3687
3688 Note that passing "execute" an empty array is the same as passing no
3689 arguments at all, which will execute the statement with previously
3690 bound values. That's probably not what you want.
3691
3692 If execute() is called on a statement handle that's still active
3693 ($sth->{Active} is true) then it should effectively call finish() to
3694 tidy up the previous execution results before starting this new
3695 execution.
3696
3697 "execute_array"
3698
3699 $tuples = $sth->execute_array(\%attr) or die $sth->errstr;
3700 $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
3701
3702 ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr;
3703 ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
3704
3705 Execute the prepared statement once for each parameter tuple (group of
3706 values) provided either in the @bind_values, or by prior calls to
3707 "bind_param_array", or via a reference passed in \%attr.
3708
3709 When called in scalar context the execute_array() method returns the
3710 number of tuples executed, or "undef" if an error occurred. Like
3711 execute(), a successful execute_array() always returns true regardless
3712 of the number of tuples executed, even if it's zero. If there were any
3713 errors the ArrayTupleStatus array can be used to discover which tuples
3714 failed and with what errors.
3715
3716 When called in list context the execute_array() method returns two
3717 scalars; $tuples is the same as calling execute_array() in scalar
3718 context and $rows is the sum of the number of rows affected for each
3719 tuple, if available or -1 if the driver cannot determine this. If you
3720 are doing an update operation the returned rows affected may not be
3721 what you expect if, for instance, one or more of the tuples affected
3722 the same row multiple times. Some drivers may not yet support list
3723 context, in which case $rows will be undef, or may not be able to
3724 provide the number of rows affected when performing this batch
3725 operation, in which case $rows will be -1.
3726
3727 Bind values for the tuples to be executed may be supplied row-wise by
3728 an "ArrayTupleFetch" attribute, or else column-wise in the @bind_values
3729 argument, or else column-wise by prior calls to "bind_param_array".
3730
3731 Where column-wise binding is used (via the @bind_values argument or
3732 calls to bind_param_array()) the maximum number of elements in any one
3733 of the bound value arrays determines the number of tuples executed.
3734 Placeholders with fewer values in their parameter arrays are treated as
3735 if padded with undef (NULL) values.
3736
3737 If a scalar value is bound, instead of an array reference, it is
3738 treated as a variable length array with all elements having the same
3739 value. It's does not influence the number of tuples executed, so if all
3740 bound arrays have zero elements then zero tuples will be executed. If
3741 all bound values are scalars then one tuple will be executed, making
3742 execute_array() act just like execute().
3743
3744 The "ArrayTupleFetch" attribute can be used to specify a reference to a
3745 subroutine that will be called to provide the bind values for each
3746 tuple execution. The subroutine should return an reference to an array
3747 which contains the appropriate number of bind values, or return an
3748 undef if there is no more data to execute.
3749
3750 As a convenience, the "ArrayTupleFetch" attribute can also be used to
3751 specify a statement handle. In which case the fetchrow_arrayref()
3752 method will be called on the given statement handle in order to provide
3753 the bind values for each tuple execution.
3754
3755 The values specified via bind_param_array() or the @bind_values
3756 parameter may be either scalars, or arrayrefs. If any @bind_values are
3757 given, then "execute_array" will effectively call "bind_param_array"
3758 for each value before executing the statement. Values bound in this
3759 way are usually treated as "SQL_VARCHAR" types unless the driver can
3760 determine the correct type (which is rare), or unless "bind_param",
3761 "bind_param_inout", "bind_param_array", or "bind_param_inout_array" has
3762 already been used to specify the type. See "bind_param_array" for
3763 details.
3764
3765 The "ArrayTupleStatus" attribute can be used to specify a reference to
3766 an array which will receive the execute status of each executed
3767 parameter tuple. Note the "ArrayTupleStatus" attribute was mandatory
3768 until DBI 1.38.
3769
3770 For tuples which are successfully executed, the element at the same
3771 ordinal position in the status array is the resulting rowcount. If the
3772 execution of a tuple causes an error, then the corresponding status
3773 array element will be set to a reference to an array containing the
3774 error code and error string set by the failed execution.
3775
3776 If any tuple execution returns an error, "execute_array" will return
3777 "undef". In that case, the application should inspect the status array
3778 to determine which parameter tuples failed. Some databases may not
3779 continue executing tuples beyond the first failure. In this case the
3780 status array will either hold fewer elements, or the elements beyond
3781 the failure will be undef.
3782
3783 If all parameter tuples are successfully executed, "execute_array"
3784 returns the number tuples executed. If no tuples were executed, then
3785 execute_array() returns "0E0", just like execute() does, which Perl
3786 will treat as 0 but will regard as true.
3787
3788 For example:
3789
3790 $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)");
3791 my $tuples = $sth->execute_array(
3792 { ArrayTupleStatus => \my @tuple_status },
3793 \@first_names,
3794 \@last_names,
3795 );
3796 if ($tuples) {
3797 print "Successfully inserted $tuples records\n";
3798 }
3799 else {
3800 for my $tuple (0..@last_names-1) {
3801 my $status = $tuple_status[$tuple];
3802 $status = [0, "Skipped"] unless defined $status;
3803 next unless ref $status;
3804 printf "Failed to insert (%s, %s): %s\n",
3805 $first_names[$tuple], $last_names[$tuple], $status->[1];
3806 }
3807 }
3808
3809 Support for data returning statements such as SELECT is driver-specific
3810 and subject to change. At present, the default implementation provided
3811 by DBI only supports non-data returning statements.
3812
3813 Transaction semantics when using array binding are driver and database
3814 specific. If "AutoCommit" is on, the default DBI implementation will
3815 cause each parameter tuple to be individually committed (or rolled back
3816 in the event of an error). If "AutoCommit" is off, the application is
3817 responsible for explicitly committing the entire set of bound parameter
3818 tuples. Note that different drivers and databases may have different
3819 behaviours when some parameter tuples cause failures. In some cases,
3820 the driver or database may automatically rollback the effect of all
3821 prior parameter tuples that succeeded in the transaction; other drivers
3822 or databases may retain the effect of prior successfully executed
3823 parameter tuples. Be sure to check your driver and database for its
3824 specific behaviour.
3825
3826 Note that, in general, performance will usually be better with
3827 "AutoCommit" turned off, and using explicit "commit" after each
3828 "execute_array" call.
3829
3830 The "execute_array" method was added in DBI 1.22, and ArrayTupleFetch
3831 was added in 1.36.
3832
3833 "execute_for_fetch"
3834
3835 $tuples = $sth->execute_for_fetch($fetch_tuple_sub);
3836 $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
3837
3838 ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub);
3839 ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
3840
3841 The execute_for_fetch() method is used to perform bulk operations and
3842 is most often used via the execute_array() method, not directly.
3843
3844 The fetch subroutine, referenced by $fetch_tuple_sub, is expected to
3845 return a reference to an array (known as a 'tuple') or undef.
3846
3847 The execute_for_fetch() method calls $fetch_tuple_sub, without any
3848 parameters, until it returns a false value. Each tuple returned is used
3849 to provide bind values for an $sth->execute(@$tuple) call.
3850
3851 In scalar context execute_for_fetch() returns "undef" if there were any
3852 errors and the number of tuples executed otherwise. Like execute() and
3853 execute_array() a zero is returned as "0E0" so execute_for_fetch() is
3854 only false on error. If there were any errors the @tuple_status array
3855 can be used to discover which tuples failed and with what errors.
3856
3857 When called in list context execute_for_fetch() returns two scalars;
3858 $tuples is the same as calling execute_for_fetch() in scalar context
3859 and $rows is the sum of the number of rows affected for each tuple, if
3860 available or -1 if the driver cannot determine this. If you are doing
3861 an update operation the returned rows affected may not be what you
3862 expect if, for instance, one or more of the tuples affected the same
3863 row multiple times. Some drivers may not yet support list context, in
3864 which case $rows will be undef, or may not be able to provide the
3865 number of rows affected when performing this batch operation, in which
3866 case $rows will be -1.
3867
3868 If \@tuple_status is passed then the execute_for_fetch method uses it
3869 to return status information. The tuple_status array holds one element
3870 per tuple. If the corresponding execute() did not fail then the element
3871 holds the return value from execute(), which is typically a row count.
3872 If the execute() did fail then the element holds a reference to an
3873 array containing ($sth->err, $sth->errstr, $sth->state).
3874
3875 If the driver detects an error that it knows means no further tuples
3876 can be executed then it may return, with an error status, even though
3877 $fetch_tuple_sub may still have more tuples to be executed.
3878
3879 Although each tuple returned by $fetch_tuple_sub is effectively used to
3880 call $sth->execute(@$tuple_array_ref) the exact timing may vary.
3881 Drivers are free to accumulate sets of tuples to pass to the database
3882 server in bulk group operations for more efficient execution. However,
3883 the $fetch_tuple_sub is specifically allowed to return the same array
3884 reference each time (which is what fetchrow_arrayref() usually does).
3885
3886 For example:
3887
3888 my $sel = $dbh1->prepare("select foo, bar from table1");
3889 $sel->execute;
3890
3891 my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)");
3892 my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref };
3893
3894 my @tuple_status;
3895 $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
3896 my @errors = grep { ref $_ } @tuple_status;
3897
3898 Similarly, if you already have an array containing the data rows to be
3899 processed you'd use a subroutine to shift off and return each array ref
3900 in turn:
3901
3902 $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status);
3903
3904 The "execute_for_fetch" method was added in DBI 1.38.
3905
3906 "fetchrow_arrayref"
3907
3908 $ary_ref = $sth->fetchrow_arrayref;
3909 $ary_ref = $sth->fetch; # alias
3910
3911 Fetches the next row of data and returns a reference to an array
3912 holding the field values. Null fields are returned as "undef" values
3913 in the array. This is the fastest way to fetch data, particularly if
3914 used with "$sth->bind_columns".
3915
3916 If there are no more rows or if an error occurs, then
3917 "fetchrow_arrayref" returns an "undef". You should check "$sth->err"
3918 afterwards (or use the "RaiseError" attribute) to discover if the
3919 "undef" returned was due to an error.
3920
3921 Note that the same array reference is returned for each fetch, so don't
3922 store the reference and then use it after a later fetch. Also, the
3923 elements of the array are also reused for each row, so take care if you
3924 want to take a reference to an element. See also "bind_columns".
3925
3926 "fetchrow_array"
3927
3928 @ary = $sth->fetchrow_array;
3929
3930 An alternative to "fetchrow_arrayref". Fetches the next row of data and
3931 returns it as a list containing the field values. Null fields are
3932 returned as "undef" values in the list.
3933
3934 If there are no more rows or if an error occurs, then "fetchrow_array"
3935 returns an empty list. You should check "$sth->err" afterwards (or use
3936 the "RaiseError" attribute) to discover if the empty list returned was
3937 due to an error.
3938
3939 If called in a scalar context for a statement handle that has more than
3940 one column, it is undefined whether the driver will return the value of
3941 the first column or the last. So don't do that. Also, in a scalar
3942 context, an "undef" is returned if there are no more rows or if an
3943 error occurred. That "undef" can't be distinguished from an "undef"
3944 returned because the first field value was NULL. For these reasons you
3945 should exercise some caution if you use "fetchrow_array" in a scalar
3946 context.
3947
3948 "fetchrow_hashref"
3949
3950 $hash_ref = $sth->fetchrow_hashref;
3951 $hash_ref = $sth->fetchrow_hashref($name);
3952
3953 An alternative to "fetchrow_arrayref". Fetches the next row of data and
3954 returns it as a reference to a hash containing field name and field
3955 value pairs. Null fields are returned as "undef" values in the hash.
3956
3957 If there are no more rows or if an error occurs, then
3958 "fetchrow_hashref" returns an "undef". You should check "$sth->err"
3959 afterwards (or use the "RaiseError" attribute) to discover if the
3960 "undef" returned was due to an error.
3961
3962 The optional $name parameter specifies the name of the statement handle
3963 attribute. For historical reasons it defaults to ""NAME"", however
3964 using either ""NAME_lc"" or ""NAME_uc"" is recomended for portability.
3965
3966 The keys of the hash are the same names returned by "$sth->{$name}". If
3967 more than one field has the same name, there will only be one entry in
3968 the returned hash for those fields.
3969
3970 Because of the extra work "fetchrow_hashref" and Perl have to perform,
3971 it is not as efficient as "fetchrow_arrayref" or "fetchrow_array".
3972
3973 By default a reference to a new hash is returned for each row. It is
3974 likely that a future version of the DBI will support an attribute which
3975 will enable the same hash to be reused for each row. This will give a
3976 significant performance boost, but it won't be enabled by default
3977 because of the risk of breaking old code.
3978
3979 "fetchall_arrayref"
3980
3981 $tbl_ary_ref = $sth->fetchall_arrayref;
3982 $tbl_ary_ref = $sth->fetchall_arrayref( $slice );
3983 $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
3984
3985 The "fetchall_arrayref" method can be used to fetch all the data to be
3986 returned from a prepared and executed statement handle. It returns a
3987 reference to an array that contains one reference per row.
3988
3989 If there are no rows to return, "fetchall_arrayref" returns a reference
3990 to an empty array. If an error occurs, "fetchall_arrayref" returns the
3991 data fetched thus far, which may be none. You should check "$sth->err"
3992 afterwards (or use the "RaiseError" attribute) to discover if the data
3993 is complete or was truncated due to an error.
3994
3995 If $slice is an array reference, "fetchall_arrayref" uses
3996 "fetchrow_arrayref" to fetch each row as an array ref. If the $slice
3997 array is not empty then it is used as a slice to select individual
3998 columns by perl array index number (starting at 0, unlike column and
3999 parameter numbers which start at 1).
4000
4001 With no parameters, or if $slice is undefined, "fetchall_arrayref" acts
4002 as if passed an empty array ref.
4003
4004 If $slice is a hash reference, "fetchall_arrayref" uses
4005 "fetchrow_hashref" to fetch each row as a hash reference. If the $slice
4006 hash is empty then fetchrow_hashref() is simply called in a tight loop
4007 and the keys in the hashes have whatever name lettercase is returned by
4008 default from fetchrow_hashref. (See "FetchHashKeyName" attribute.) If
4009 the $slice hash is not empty, then it is used as a slice to select
4010 individual columns by name. The values of the hash should be set to 1.
4011 The key names of the returned hashes match the letter case of the names
4012 in the parameter hash, regardless of the "FetchHashKeyName" attribute.
4013
4014 For example, to fetch just the first column of every row:
4015
4016 $tbl_ary_ref = $sth->fetchall_arrayref([0]);
4017
4018 To fetch the second to last and last column of every row:
4019
4020 $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
4021
4022 To fetch all fields of every row as a hash ref:
4023
4024 $tbl_ary_ref = $sth->fetchall_arrayref({});
4025
4026 To fetch only the fields called "foo" and "bar" of every row as a hash
4027 ref (with keys named "foo" and "BAR"):
4028
4029 $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 });
4030
4031 The first two examples return a reference to an array of array refs.
4032 The third and forth return a reference to an array of hash refs.
4033
4034 If $max_rows is defined and greater than or equal to zero then it is
4035 used to limit the number of rows fetched before returning.
4036 fetchall_arrayref() can then be called again to fetch more rows. This
4037 is especially useful when you need the better performance of
4038 fetchall_arrayref() but don't have enough memory to fetch and return
4039 all the rows in one go.
4040
4041 Here's an example (assumes RaiseError is enabled):
4042
4043 my $rows = []; # cache for batches of rows
4044 while( my $row = ( shift(@$rows) || # get row from cache, or reload cache:
4045 shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) )
4046 ) {
4047 ...
4048 }
4049
4050 That might be the fastest way to fetch and process lots of rows using
4051 the DBI, but it depends on the relative cost of method calls vs memory
4052 allocation.
4053
4054 A standard "while" loop with column binding is often faster because the
4055 cost of allocating memory for the batch of rows is greater than the
4056 saving by reducing method calls. It's possible that the DBI may provide
4057 a way to reuse the memory of a previous batch in future, which would
4058 then shift the balance back towards fetchall_arrayref().
4059
4060 "fetchall_hashref"
4061
4062 $hash_ref = $sth->fetchall_hashref($key_field);
4063
4064 The "fetchall_hashref" method can be used to fetch all the data to be
4065 returned from a prepared and executed statement handle. It returns a
4066 reference to a hash containing a key for each distinct value of the
4067 $key_field column that was fetched. For each key the corresponding
4068 value is a reference to a hash containing all the selected columns and
4069 their values, as returned by fetchrow_hashref().
4070
4071 If there are no rows to return, "fetchall_hashref" returns a reference
4072 to an empty hash. If an error occurs, "fetchall_hashref" returns the
4073 data fetched thus far, which may be none. You should check "$sth->err"
4074 afterwards (or use the "RaiseError" attribute) to discover if the data
4075 is complete or was truncated due to an error.
4076
4077 The $key_field parameter provides the name of the field that holds the
4078 value to be used for the key for the returned hash. For example:
4079
4080 $dbh->{FetchHashKeyName} = 'NAME_lc';
4081 $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE");
4082 $sth->execute;
4083 $hash_ref = $sth->fetchall_hashref('id');
4084 print "Name for id 42 is $hash_ref->{42}->{name}\n";
4085
4086 The $key_field parameter can also be specified as an integer column
4087 number (counting from 1). If $key_field doesn't match any column in
4088 the statement, as a name first then as a number, then an error is
4089 returned.
4090
4091 For queries returning more than one 'key' column, you can specify
4092 multiple column names by passing $key_field as a reference to an array
4093 containing one or more key column names (or index numbers). For
4094 example:
4095
4096 $sth = $dbh->prepare("SELECT foo, bar, baz FROM table");
4097 $sth->execute;
4098 $hash_ref = $sth->fetchall_hashref( [ qw(foo bar) ] );
4099 print "For foo 42 and bar 38, baz is $hash_ref->{42}->{38}->{baz}\n";
4100
4101 The fetchall_hashref() method is normally used only where the key
4102 fields values for each row are unique. If multiple rows are returned
4103 with the same values for the key fields then later rows overwrite
4104 earlier ones.
4105
4106 "finish"
4107
4108 $rc = $sth->finish;
4109
4110 Indicate that no more data will be fetched from this statement handle
4111 before it is either executed again or destroyed. The "finish" method
4112 is rarely needed, and frequently overused, but can sometimes be helpful
4113 in a few very specific situations to allow the server to free up
4114 resources (such as sort buffers).
4115
4116 When all the data has been fetched from a "SELECT" statement, the
4117 driver should automatically call "finish" for you. So you should not
4118 normally need to call it explicitly except when you know that you've
4119 not fetched all the data from a statement handle. The most common
4120 example is when you only want to fetch one row, but in that case the
4121 "selectrow_*" methods are usually better anyway. Adding calls to
4122 "finish" after each fetch loop is a common mistake, don't do it, it can
4123 mask genuine problems like uncaught fetch errors.
4124
4125 Consider a query like:
4126
4127 SELECT foo FROM table WHERE bar=? ORDER BY foo
4128
4129 where you want to select just the first (smallest) "foo" value from a
4130 very large table. When executed, the database server will have to use
4131 temporary buffer space to store the sorted rows. If, after executing
4132 the handle and selecting one row, the handle won't be re-executed for
4133 some time and won't be destroyed, the "finish" method can be used to
4134 tell the server that the buffer space can be freed.
4135
4136 Calling "finish" resets the "Active" attribute for the statement. It
4137 may also make some statement handle attributes (such as "NAME" and
4138 "TYPE") unavailable if they have not already been accessed (and thus
4139 cached).
4140
4141 The "finish" method does not affect the transaction status of the
4142 database connection. It has nothing to do with transactions. It's
4143 mostly an internal "housekeeping" method that is rarely needed. See
4144 also "disconnect" and the "Active" attribute.
4145
4146 The "finish" method should have been called "discard_pending_rows".
4147
4148 "rows"
4149
4150 $rv = $sth->rows;
4151
4152 Returns the number of rows affected by the last row affecting command,
4153 or -1 if the number of rows is not known or not available.
4154
4155 Generally, you can only rely on a row count after a non-"SELECT"
4156 "execute" (for some specific operations like "UPDATE" and "DELETE"), or
4157 after fetching all the rows of a "SELECT" statement.
4158
4159 For "SELECT" statements, it is generally not possible to know how many
4160 rows will be returned except by fetching them all. Some drivers will
4161 return the number of rows the application has fetched so far, but
4162 others may return -1 until all rows have been fetched. So use of the
4163 "rows" method or $DBI::rows with "SELECT" statements is not
4164 recommended.
4165
4166 One alternative method to get a row count for a "SELECT" is to execute
4167 a "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your
4168 query and then fetch the row count from that.
4169
4170 "bind_col"
4171
4172 $rc = $sth->bind_col($column_number, \$var_to_bind);
4173 $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr );
4174 $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type );
4175
4176 Binds a Perl variable and/or some attributes to an output column
4177 (field) of a "SELECT" statement. Column numbers count up from 1. You
4178 do not need to bind output columns in order to fetch data. For maximum
4179 portability between drivers, bind_col() should be called after
4180 execute() and not before. See also "bind_columns" for an example.
4181
4182 The binding is performed at a low level using Perl aliasing. Whenever
4183 a row is fetched from the database $var_to_bind appears to be
4184 automatically updated simply because it now refers to the same memory
4185 location as the corresponding column value. This makes using bound
4186 variables very efficient. Binding a tied variable doesn't work,
4187 currently.
4188
4189 The "bind_param" method performs a similar, but opposite, function for
4190 input variables.
4191
4192 Data Types for Column Binding
4193
4194 The "\%attr" parameter can be used to hint at the data type formatting
4195 the column should have. For example, you can use:
4196
4197 $sth->bind_col(1, undef, { TYPE => SQL_DATETIME });
4198
4199 to specify that you'd like the column (which presumably is some kind of
4200 datetime type) to be returned in the standard format for SQL_DATETIME,
4201 which is 'YYYY-MM-DD HH:MM:SS', rather than the native formatting the
4202 database would normally use.
4203
4204 There's no $var_to_bind in that example to emphasize the point that
4205 bind_col() works on the underlying column and not just a particular
4206 bound variable.
4207
4208 As a short-cut for the common case, the data type can be passed
4209 directly, in place of the "\%attr" hash reference. This example is
4210 equivalent to the one above:
4211
4212 $sth->bind_col(1, undef, SQL_DATETIME);
4213
4214 The "TYPE" value indicates the standard (non-driver-specific) type for
4215 this parameter. To specify the driver-specific type, the driver may
4216 support a driver-specific attribute, such as "{ ora_type => 97 }".
4217
4218 The SQL_DATETIME and other related constants can be imported using
4219
4220 use DBI qw(:sql_types);
4221
4222 See "DBI Constants" for more information.
4223
4224 Few drivers support specifying a data type via a "bind_col" call (most
4225 will simply ignore the data type). Fewer still allow the data type to
4226 be altered once set.
4227
4228 The TYPE attribute for bind_col() was first specified in DBI 1.41.
4229
4230 "bind_columns"
4231
4232 $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
4233
4234 Calls "bind_col" for each column of the "SELECT" statement.
4235
4236 The list of references should have the same number of elements as the
4237 number of columns in the "SELECT" statement. If it doesn't then
4238 "bind_columns" will bind the elements given, up to the number of
4239 columns, and then return an error.
4240
4241 For maximum portability between drivers, bind_columns() should be
4242 called after execute() and not before.
4243
4244 For example:
4245
4246 $dbh->{RaiseError} = 1; # do this, or check every call for errors
4247 $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
4248 $sth->execute;
4249 my ($region, $sales);
4250
4251 # Bind Perl variables to columns:
4252 $rv = $sth->bind_columns(\$region, \$sales);
4253
4254 # you can also use Perl's \(...) syntax (see perlref docs):
4255 # $sth->bind_columns(\($region, $sales));
4256
4257 # Column binding is the most efficient way to fetch data
4258 while ($sth->fetch) {
4259 print "$region: $sales\n";
4260 }
4261
4262 For compatibility with old scripts, the first parameter will be ignored
4263 if it is "undef" or a hash reference.
4264
4265 Here's a more fancy example that binds columns to the values inside a
4266 hash (thanks to H.Merijn Brand):
4267
4268 $sth->execute;
4269 my %row;
4270 $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } ));
4271 while ($sth->fetch) {
4272 print "$row{region}: $row{sales}\n";
4273 }
4274
4275 "dump_results"
4276
4277 $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
4278
4279 Fetches all the rows from $sth, calls "DBI::neat_list" for each row,
4280 and prints the results to $fh (defaults to "STDOUT") separated by $lsep
4281 (default "\n"). $fsep defaults to ", " and $maxlen defaults to 35.
4282
4283 This method is designed as a handy utility for prototyping and testing
4284 queries. Since it uses "neat_list" to format and edit the string for
4285 reading by humans, it is not recommended for data transfer
4286 applications.
4287
4288 Statement Handle Attributes
4289 This section describes attributes specific to statement handles. Most
4290 of these attributes are read-only.
4291
4292 Changes to these statement handle attributes do not affect any other
4293 existing or future statement handles.
4294
4295 Attempting to set or get the value of an unknown attribute generates a
4296 warning, except for private driver specific attributes (which all have
4297 names starting with a lowercase letter).
4298
4299 Example:
4300
4301 ... = $h->{NUM_OF_FIELDS}; # get/read
4302
4303 Some drivers cannot provide valid values for some or all of these
4304 attributes until after "$sth->execute" has been successfully called.
4305 Typically the attribute will be "undef" in these situations.
4306
4307 Some attributes, like NAME, are not appropriate to some types of
4308 statement, like SELECT. Typically the attribute will be "undef" in
4309 these situations.
4310
4311 For drivers which support stored procedures and multiple result sets
4312 (see "more_results") these attributes relate to the current result set.
4313
4314 See also "finish" to learn more about the effect it may have on some
4315 attributes.
4316
4317 "NUM_OF_FIELDS" (integer, read-only)
4318
4319 Number of fields (columns) in the data the prepared statement may
4320 return. Statements that don't return rows of data, like "DELETE" and
4321 "CREATE" set "NUM_OF_FIELDS" to 0 (though it may be undef in some
4322 drivers).
4323
4324 "NUM_OF_PARAMS" (integer, read-only)
4325
4326 The number of parameters (placeholders) in the prepared statement. See
4327 SUBSTITUTION VARIABLES below for more details.
4328
4329 "NAME" (array-ref, read-only)
4330
4331 Returns a reference to an array of field names for each column. The
4332 names may contain spaces but should not be truncated or have any
4333 trailing space. Note that the names have the letter case (upper, lower
4334 or mixed) as returned by the driver being used. Portable applications
4335 should use "NAME_lc" or "NAME_uc".
4336
4337 print "First column name: $sth->{NAME}->[0]\n";
4338
4339 "NAME_lc" (array-ref, read-only)
4340
4341 Like "NAME" but always returns lowercase names.
4342
4343 "NAME_uc" (array-ref, read-only)
4344
4345 Like "NAME" but always returns uppercase names.
4346
4347 "NAME_hash" (hash-ref, read-only)
4348
4349 "NAME_lc_hash" (hash-ref, read-only)
4350
4351 "NAME_uc_hash" (hash-ref, read-only)
4352
4353 The "NAME_hash", "NAME_lc_hash", and "NAME_uc_hash" attributes return
4354 column name information as a reference to a hash.
4355
4356 The keys of the hash are the names of the columns. The letter case of
4357 the keys corresponds to the letter case returned by the "NAME",
4358 "NAME_lc", and "NAME_uc" attributes respectively (as described above).
4359
4360 The value of each hash entry is the perl index number of the
4361 corresponding column (counting from 0). For example:
4362
4363 $sth = $dbh->prepare("select Id, Name from table");
4364 $sth->execute;
4365 @row = $sth->fetchrow_array;
4366 print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n";
4367
4368 "TYPE" (array-ref, read-only)
4369
4370 Returns a reference to an array of integer values for each column. The
4371 value indicates the data type of the corresponding column.
4372
4373 The values correspond to the international standards (ANSI X3.135 and
4374 ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific
4375 types that don't exactly match standard types should generally return
4376 the same values as an ODBC driver supplied by the makers of the
4377 database. That might include private type numbers in ranges the vendor
4378 has officially registered with the ISO working group:
4379
4380 ftp://sqlstandards.org/SC32/SQL_Registry/
4381
4382 Where there's no vendor-supplied ODBC driver to be compatible with, the
4383 DBI driver can use type numbers in the range that is now officially
4384 reserved for use by the DBI: -9999 to -9000.
4385
4386 All possible values for "TYPE" should have at least one entry in the
4387 output of the "type_info_all" method (see "type_info_all").
4388
4389 "PRECISION" (array-ref, read-only)
4390
4391 Returns a reference to an array of integer values for each column.
4392
4393 For numeric columns, the value is the maximum number of digits (without
4394 considering a sign character or decimal point). Note that the "display
4395 size" for floating point types (REAL, FLOAT, DOUBLE) can be up to 7
4396 characters greater than the precision (for the sign + decimal point +
4397 the letter E + a sign + 2 or 3 digits).
4398
4399 For any character type column the value is the OCTET_LENGTH, in other
4400 words the number of bytes, not characters.
4401
4402 (More recent standards refer to this as COLUMN_SIZE but we stick with
4403 PRECISION for backwards compatibility.)
4404
4405 "SCALE" (array-ref, read-only)
4406
4407 Returns a reference to an array of integer values for each column.
4408 NULL ("undef") values indicate columns where scale is not applicable.
4409
4410 "NULLABLE" (array-ref, read-only)
4411
4412 Returns a reference to an array indicating the possibility of each
4413 column returning a null. Possible values are 0 (or an empty string) =
4414 no, 1 = yes, 2 = unknown.
4415
4416 print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
4417
4418 "CursorName" (string, read-only)
4419
4420 Returns the name of the cursor associated with the statement handle, if
4421 available. If not available or if the database driver does not support
4422 the "where current of ..." SQL syntax, then it returns "undef".
4423
4424 "Database" (dbh, read-only)
4425
4426 Returns the parent $dbh of the statement handle.
4427
4428 "Statement" (string, read-only)
4429
4430 Returns the statement string passed to the "prepare" method.
4431
4432 "ParamValues" (hash ref, read-only)
4433
4434 Returns a reference to a hash containing the values currently bound to
4435 placeholders. The keys of the hash are the 'names' of the
4436 placeholders, typically integers starting at 1. Returns undef if not
4437 supported by the driver.
4438
4439 See "ShowErrorStatement" for an example of how this is used.
4440
4441 * Keys:
4442
4443 If the driver supports "ParamValues" but no values have been bound yet
4444 then the driver should return a hash with placeholders names in the
4445 keys but all the values undef, but some drivers may return a ref to an
4446 empty hash because they can't pre-determine the names.
4447
4448 It is possible that the keys in the hash returned by "ParamValues" are
4449 not exactly the same as those implied by the prepared statement. For
4450 example, DBD::Oracle translates '"?"' placeholders into '":pN"' where N
4451 is a sequence number starting at 1.
4452
4453 * Values:
4454
4455 It is possible that the values in the hash returned by "ParamValues"
4456 are not exactly the same as those passed to bind_param() or execute().
4457 The driver may have slightly modified values in some way based on the
4458 TYPE the value was bound with. For example a floating point value bound
4459 as an SQL_INTEGER type may be returned as an integer. The values
4460 returned by "ParamValues" can be passed to another bind_param() method
4461 with the same TYPE and will be seen by the database as the same value.
4462 See also "ParamTypes" below.
4463
4464 The "ParamValues" attribute was added in DBI 1.28.
4465
4466 "ParamTypes" (hash ref, read-only)
4467
4468 Returns a reference to a hash containing the type information currently
4469 bound to placeholders. Returns undef if not supported by the driver.
4470
4471 * Keys:
4472
4473 See "ParamValues" above.
4474
4475 * Values:
4476
4477 The hash values are hashrefs of type information in the same form as
4478 that passed to the various bind_param() methods (See "bind_param" for
4479 the format and values).
4480
4481 It is possible that the values in the hash returned by "ParamTypes" are
4482 not exactly the same as those passed to bind_param() or execute().
4483 Param attributes specified using the abreviated form, like this:
4484
4485 $sth->bind_param(1, SQL_INTEGER);
4486
4487 are returned in the expanded form, as if called like this:
4488
4489 $sth->bind_param(1, { TYPE => SQL_INTEGER });
4490
4491 The driver may have modified the type information in some way based on
4492 the bound values, other hints provided by the prepare()'d SQL
4493 statement, or alternate type mappings required by the driver or target
4494 database system. The driver may also add private keys (with names
4495 beginning with the drivers reserved prefix, e.g., odbc_xxx).
4496
4497 * Example:
4498
4499 The keys and values in the returned hash can be passed to the various
4500 bind_param() methods to effectively reproduce a previous param binding.
4501 For example:
4502
4503 # assuming $sth1 is a previously prepared statement handle
4504 my $sth2 = $dbh->prepare( $sth1->{Statement} );
4505 my $ParamValues = $sth1->{ParamValues} || {};
4506 my $ParamTypes = $sth1->{ParamTypes} || {};
4507 $sth2->bind_param($_, $PV->{$_} $PT->{$_})
4508 for keys %{ %$PV, %$PT };
4509 $sth2->execute();
4510
4511 The "ParamTypes" attribute was added in DBI 1.49. Implementation is the
4512 responsibility of individual drivers; the DBI layer default
4513 implementation simply returns undef.
4514
4515 "ParamArrays" (hash ref, read-only)
4516
4517 Returns a reference to a hash containing the values currently bound to
4518 placeholders with "execute_array" or "bind_param_array". The keys of
4519 the hash are the 'names' of the placeholders, typically integers
4520 starting at 1. Returns undef if not supported by the driver or no
4521 arrays of parameters are bound.
4522
4523 Each key value is an array reference containing a list of the bound
4524 parameters for that column.
4525
4526 For example:
4527
4528 $sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)");
4529 $sth->execute_array({},[1,2], ['fred','dave']);
4530 if ($sth->{ParamArrays}) {
4531 foreach $param (keys %{$sth->{ParamArrays}}) {
4532 printf "Parameters for %s : %s\n", $param,
4533 join(",", @{$sth->{ParamArrays}->{$param}});
4534 }
4535 }
4536
4537 It is possible that the values in the hash returned by "ParamArrays"
4538 are not exactly the same as those passed to "bind_param_array" or
4539 "execute_array". The driver may have slightly modified values in some
4540 way based on the TYPE the value was bound with. For example a floating
4541 point value bound as an SQL_INTEGER type may be returned as an integer.
4542
4543 It is also possible that the keys in the hash returned by "ParamArrays"
4544 are not exactly the same as those implied by the prepared statement.
4545 For example, DBD::Oracle translates '"?"' placeholders into '":pN"'
4546 where N is a sequence number starting at 1.
4547
4548 "RowsInCache" (integer, read-only)
4549
4550 If the driver supports a local row cache for "SELECT" statements, then
4551 this attribute holds the number of un-fetched rows in the cache. If the
4552 driver doesn't, then it returns "undef". Note that some drivers pre-
4553 fetch rows on execute, whereas others wait till the first fetch.
4554
4555 See also the "RowCacheSize" database handle attribute.
4556
4558 Catalog Methods
4559 An application can retrieve metadata information from the DBMS by
4560 issuing appropriate queries on the views of the Information Schema.
4561 Unfortunately, "INFORMATION_SCHEMA" views are seldom supported by the
4562 DBMS. Special methods (catalog methods) are available to return result
4563 sets for a small but important portion of that metadata:
4564
4565 column_info
4566 foreign_key_info
4567 primary_key_info
4568 table_info
4569 statistics_info
4570
4571 All catalog methods accept arguments in order to restrict the result
4572 sets. Passing "undef" to an optional argument does not constrain the
4573 search for that argument. However, an empty string ('') is treated as
4574 a regular search criteria and will only match an empty value.
4575
4576 Note: SQL/CLI and ODBC differ in the handling of empty strings. An
4577 empty string will not restrict the result set in SQL/CLI.
4578
4579 Most arguments in the catalog methods accept only ordinary values, e.g.
4580 the arguments of "primary_key_info()". Such arguments are treated as a
4581 literal string, i.e. the case is significant and quote characters are
4582 taken literally.
4583
4584 Some arguments in the catalog methods accept search patterns (strings
4585 containing '_' and/or '%'), e.g. the $table argument of
4586 "column_info()". Passing '%' is equivalent to leaving the argument
4587 "undef".
4588
4589 Caveat: The underscore ('_') is valid and often used in SQL
4590 identifiers. Passing such a value to a search pattern argument may
4591 return more rows than expected! To include pattern characters as
4592 literals, they must be preceded by an escape character which can be
4593 achieved with
4594
4595 $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE
4596 $search_pattern =~ s/([_%])/$esc$1/g;
4597
4598 The ODBC and SQL/CLI specifications define a way to change the default
4599 behaviour described above: All arguments (except list value arguments)
4600 are treated as identifier if the "SQL_ATTR_METADATA_ID" attribute is
4601 set to "SQL_TRUE". Quoted identifiers are very similar to ordinary
4602 values, i.e. their body (the string within the quotes) is interpreted
4603 literally. Unquoted identifiers are compared in UPPERCASE.
4604
4605 The DBI (currently) does not support the "SQL_ATTR_METADATA_ID"
4606 attribute, i.e. it behaves like an ODBC driver where
4607 "SQL_ATTR_METADATA_ID" is set to "SQL_FALSE".
4608
4609 Transactions
4610 Transactions are a fundamental part of any robust database system. They
4611 protect against errors and database corruption by ensuring that sets of
4612 related changes to the database take place in atomic (indivisible, all-
4613 or-nothing) units.
4614
4615 This section applies to databases that support transactions and where
4616 "AutoCommit" is off. See "AutoCommit" for details of using
4617 "AutoCommit" with various types of databases.
4618
4619 The recommended way to implement robust transactions in Perl
4620 applications is to use "RaiseError" and "eval { ... }" (which is very
4621 fast, unlike "eval "...""). For example:
4622
4623 $dbh->{AutoCommit} = 0; # enable transactions, if possible
4624 $dbh->{RaiseError} = 1;
4625 eval {
4626 foo(...) # do lots of work here
4627 bar(...) # including inserts
4628 baz(...) # and updates
4629 $dbh->commit; # commit the changes if we get this far
4630 };
4631 if ($@) {
4632 warn "Transaction aborted because $@";
4633 # now rollback to undo the incomplete changes
4634 # but do it in an eval{} as it may also fail
4635 eval { $dbh->rollback };
4636 # add other application on-error-clean-up code here
4637 }
4638
4639 If the "RaiseError" attribute is not set, then DBI calls would need to
4640 be manually checked for errors, typically like this:
4641
4642 $h->method(@args) or die $h->errstr;
4643
4644 With "RaiseError" set, the DBI will automatically "die" if any DBI
4645 method call on that handle (or a child handle) fails, so you don't have
4646 to test the return value of each method call. See "RaiseError" for more
4647 details.
4648
4649 A major advantage of the "eval" approach is that the transaction will
4650 be properly rolled back if any code (not just DBI calls) in the inner
4651 application dies for any reason. The major advantage of using the
4652 "$h->{RaiseError}" attribute is that all DBI calls will be checked
4653 automatically. Both techniques are strongly recommended.
4654
4655 After calling "commit" or "rollback" many drivers will not let you
4656 fetch from a previously active "SELECT" statement handle that's a child
4657 of the same database handle. A typical way round this is to connect the
4658 the database twice and use one connection for "SELECT" statements.
4659
4660 See "AutoCommit" and "disconnect" for other important information about
4661 transactions.
4662
4663 Handling BLOB / LONG / Memo Fields
4664 Many databases support "blob" (binary large objects), "long", or
4665 similar datatypes for holding very long strings or large amounts of
4666 binary data in a single field. Some databases support variable length
4667 long values over 2,000,000,000 bytes in length.
4668
4669 Since values of that size can't usually be held in memory, and because
4670 databases can't usually know in advance the length of the longest long
4671 that will be returned from a "SELECT" statement (unlike other data
4672 types), some special handling is required.
4673
4674 In this situation, the value of the "$h->{LongReadLen}" attribute is
4675 used to determine how much buffer space to allocate when fetching such
4676 fields. The "$h->{LongTruncOk}" attribute is used to determine how to
4677 behave if a fetched value can't fit into the buffer.
4678
4679 See the description of "LongReadLen" for more information.
4680
4681 When trying to insert long or binary values, placeholders should be
4682 used since there are often limits on the maximum size of an "INSERT"
4683 statement and the "quote" method generally can't cope with binary data.
4684 See "Placeholders and Bind Values".
4685
4686 Simple Examples
4687 Here's a complete example program to select and fetch some data:
4688
4689 my $data_source = "dbi::DriverName:db_name";
4690 my $dbh = DBI->connect($data_source, $user, $password)
4691 or die "Can't connect to $data_source: $DBI::errstr";
4692
4693 my $sth = $dbh->prepare( q{
4694 SELECT name, phone
4695 FROM mytelbook
4696 }) or die "Can't prepare statement: $DBI::errstr";
4697
4698 my $rc = $sth->execute
4699 or die "Can't execute statement: $DBI::errstr";
4700
4701 print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
4702 print "Field names: @{ $sth->{NAME} }\n";
4703
4704 while (($name, $phone) = $sth->fetchrow_array) {
4705 print "$name: $phone\n";
4706 }
4707 # check for problems which may have terminated the fetch early
4708 die $sth->errstr if $sth->err;
4709
4710 $dbh->disconnect;
4711
4712 Here's a complete example program to insert some data from a file.
4713 (This example uses "RaiseError" to avoid needing to check each call).
4714
4715 my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, {
4716 RaiseError => 1, AutoCommit => 0
4717 });
4718
4719 my $sth = $dbh->prepare( q{
4720 INSERT INTO table (name, phone) VALUES (?, ?)
4721 });
4722
4723 open FH, "<phone.csv" or die "Unable to open phone.csv: $!";
4724 while (<FH>) {
4725 chomp;
4726 my ($name, $phone) = split /,/;
4727 $sth->execute($name, $phone);
4728 }
4729 close FH;
4730
4731 $dbh->commit;
4732 $dbh->disconnect;
4733
4734 Here's how to convert fetched NULLs (undefined values) into empty
4735 strings:
4736
4737 while($row = $sth->fetchrow_arrayref) {
4738 # this is a fast and simple way to deal with nulls:
4739 foreach (@$row) { $_ = '' unless defined }
4740 print "@$row\n";
4741 }
4742
4743 The "q{...}" style quoting used in these examples avoids clashing with
4744 quotes that may be used in the SQL statement. Use the double-quote like
4745 "qq{...}" operator if you want to interpolate variables into the
4746 string. See "Quote and Quote-like Operators" in perlop for more
4747 details.
4748
4749 Threads and Thread Safety
4750 Perl 5.7 and later support a new threading model called iThreads. (The
4751 old "5.005 style" threads are not supported by the DBI.)
4752
4753 In the iThreads model each thread has it's own copy of the perl
4754 interpreter. When a new thread is created the original perl
4755 interpreter is 'cloned' to create a new copy for the new thread.
4756
4757 If the DBI and drivers are loaded and handles created before the thread
4758 is created then it will get a cloned copy of the DBI, the drivers and
4759 the handles.
4760
4761 However, the internal pointer data within the handles will refer to the
4762 DBI and drivers in the original interpreter. Using those handles in the
4763 new interpreter thread is not safe, so the DBI detects this and croaks
4764 on any method call using handles that don't belong to the current
4765 thread (except for DESTROY).
4766
4767 Because of this (possibly temporary) restriction, newly created threads
4768 must make their own connections to the database. Handles can't be
4769 shared across threads.
4770
4771 But BEWARE, some underlying database APIs (the code the DBD driver uses
4772 to talk to the database, often supplied by the database vendor) are not
4773 thread safe. If it's not thread safe, then allowing more than one
4774 thread to enter the code at the same time may cause subtle/serious
4775 problems. In some cases allowing more than one thread to enter the
4776 code, even if not at the same time, can cause problems. You have been
4777 warned.
4778
4779 Using DBI with perl threads is not yet recommended for production
4780 environments. For more information see
4781 <http://www.perlmonks.org/index.pl?node_id=288022>
4782
4783 Note: There is a bug in perl 5.8.2 when configured with threads and
4784 debugging enabled (bug #24463) which causes a DBI test to fail.
4785
4786 Signal Handling and Canceling Operations
4787 [The following only applies to systems with unix-like signal handling.
4788 I'd welcome additions for other systems, especially Windows.]
4789
4790 The first thing to say is that signal handling in Perl versions less
4791 than 5.8 is not safe. There is always a small risk of Perl crashing
4792 and/or core dumping when, or after, handling a signal because the
4793 signal could arrive and be handled while internal data structures are
4794 being changed. If the signal handling code used those same internal
4795 data structures it could cause all manner of subtle and not-so-subtle
4796 problems. The risk was reduced with 5.4.4 but was still present in all
4797 perls up through 5.8.0.
4798
4799 Beginning in perl 5.8.0 perl implements 'safe' signal handling if your
4800 system has the POSIX sigaction() routine. Now when a signal is
4801 delivered perl just makes a note of it but does not run the %SIG
4802 handler. The handling is 'deferred' until a 'safe' moment.
4803
4804 Although this change made signal handling safe, it also lead to a
4805 problem with signals being deferred for longer than you'd like. If a
4806 signal arrived while executing a system call, such as waiting for data
4807 on a network connection, the signal is noted and then the system call
4808 that was executing returns with an EINTR error code to indicate that it
4809 was interrupted. All fine so far.
4810
4811 The problem comes when the code that made the system call sees the
4812 EINTR code and decides it's going to call it again. Perl doesn't do
4813 that, but database code sometimes does. If that happens then the signal
4814 handler doesn't get called until later. Maybe much later.
4815
4816 Fortunately there are ways around this which we'll discuss below.
4817 Unfortunately they make signals unsafe again.
4818
4819 The two most common uses of signals in relation to the DBI are for
4820 canceling operations when the user types Ctrl-C (interrupt), and for
4821 implementing a timeout using "alarm()" and $SIG{ALRM}.
4822
4823 Cancel
4824 The DBI provides a "cancel" method for statement handles. The
4825 "cancel" method should abort the current operation and is designed
4826 to be called from a signal handler. For example:
4827
4828 $SIG{INT} = sub { $sth->cancel };
4829
4830 However, few drivers implement this (the DBI provides a default
4831 method that just returns "undef") and, even if implemented, there
4832 is still a possibility that the statement handle, and even the
4833 parent database handle, will not be usable afterwards.
4834
4835 If "cancel" returns true, then it has successfully invoked the
4836 database engine's own cancel function. If it returns false, then
4837 "cancel" failed. If it returns "undef", then the database driver
4838 does not have cancel implemented - very few do.
4839
4840 Timeout
4841 The traditional way to implement a timeout is to set $SIG{ALRM} to
4842 refer to some code that will be executed when an ALRM signal
4843 arrives and then to call alarm($seconds) to schedule an ALRM signal
4844 to be delivered $seconds in the future. For example:
4845
4846 eval {
4847 local $SIG{ALRM} = sub { die "TIMEOUT\n" };
4848 alarm($seconds);
4849 ... code to execute with timeout here ...
4850 alarm(0); # cancel alarm (if code ran fast)
4851 };
4852 alarm(0); # cancel alarm (if eval failed)
4853 if ( $@ eq "TIMEOUT\n" ) { ... }
4854
4855 Unfortunately, as described above, this won't always work as
4856 expected, depending on your perl version and the underlying
4857 database code.
4858
4859 With Oracle for instance (DBD::Oracle), if the system which hosts
4860 the database is down the DBI->connect() call will hang for several
4861 minutes before returning an error.
4862
4863 The solution on these systems is to use the "POSIX::sigaction()"
4864 routine to gain low level access to how the signal handler is
4865 installed.
4866
4867 The code would look something like this (for the DBD-Oracle connect()):
4868
4869 use POSIX ':signal_h';
4870
4871 my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler
4872 my $action = POSIX::SigAction->new(
4873 sub { die "connect timeout" }, # the handler code ref
4874 $mask,
4875 # not using (perl 5.8.2 and later) 'safe' switch or sa_flags
4876 );
4877 my $oldaction = POSIX::SigAction->new();
4878 sigaction( 'ALRM', $action, $oldaction );
4879 my $dbh;
4880 eval {
4881 alarm(5); # seconds before time out
4882 $dbh = DBI->connect("dbi:Oracle:$dsn" ... );
4883 alarm(0); # cancel alarm (if connect worked fast)
4884 };
4885 alarm(0); # cancel alarm (if eval failed)
4886 sigaction( 'ALRM', $oldaction ); # restore original signal handler
4887 if ( $@ ) ....
4888
4889 Similar techniques can be used for canceling statement execution.
4890
4891 Unfortunately, this solution is somewhat messy, and it does not work
4892 with perl versions less than perl 5.8 where "POSIX::sigaction()"
4893 appears to be broken.
4894
4895 For a cleaner implementation that works across perl versions, see
4896 Lincoln Baxter's Sys::SigAction module at
4897 <http://search.cpan.org/~lbaxter/Sys-SigAction/>. The documentation
4898 for Sys::SigAction includes an longer discussion of this problem, and a
4899 DBD::Oracle test script.
4900
4901 Be sure to read all the signal handling sections of the perlipc manual.
4902
4903 And finally, two more points to keep firmly in mind. Firstly, remember
4904 that what we've done here is essentially revert to old style unsafe
4905 handling of these signals. So do as little as possible in the handler.
4906 Ideally just die(). Secondly, the handles in use at the time the signal
4907 is handled may not be safe to use afterwards.
4908
4909 Subclassing the DBI
4910 DBI can be subclassed and extended just like any other object oriented
4911 module. Before we talk about how to do that, it's important to be
4912 clear about the various DBI classes and how they work together.
4913
4914 By default "$dbh = DBI->connect(...)" returns a $dbh blessed into the
4915 "DBI::db" class. And the "$dbh->prepare" method returns an $sth
4916 blessed into the "DBI::st" class (actually it simply changes the last
4917 four characters of the calling handle class to be "::st").
4918
4919 The leading '"DBI"' is known as the 'root class' and the extra '"::db"'
4920 or '"::st"' are the 'handle type suffixes'. If you want to subclass the
4921 DBI you'll need to put your overriding methods into the appropriate
4922 classes. For example, if you want to use a root class of "MySubDBI"
4923 and override the do(), prepare() and execute() methods, then your do()
4924 and prepare() methods should be in the "MySubDBI::db" class and the
4925 execute() method should be in the "MySubDBI::st" class.
4926
4927 To setup the inheritance hierarchy the @ISA variable in "MySubDBI::db"
4928 should include "DBI::db" and the @ISA variable in "MySubDBI::st" should
4929 include "DBI::st". The "MySubDBI" root class itself isn't currently
4930 used for anything visible and so, apart from setting @ISA to include
4931 "DBI", it can be left empty.
4932
4933 So, having put your overriding methods into the right classes, and
4934 setup the inheritance hierarchy, how do you get the DBI to use them?
4935 You have two choices, either a static method call using the name of
4936 your subclass:
4937
4938 $dbh = MySubDBI->connect(...);
4939
4940 or specifying a "RootClass" attribute:
4941
4942 $dbh = DBI->connect(..., { RootClass => 'MySubDBI' });
4943
4944 If both forms are used then the attribute takes precedence.
4945
4946 The only differences between the two are that using an explicit
4947 RootClass attribute will a) make the DBI automatically attempt to load
4948 a module by that name if the class doesn't exist, and b) won't call
4949 your MySubDBI::connect() method, if you have one.
4950
4951 When subclassing is being used then, after a successful new connect,
4952 the DBI->connect method automatically calls:
4953
4954 $dbh->connected($dsn, $user, $pass, \%attr);
4955
4956 The default method does nothing. The call is made just to simplify any
4957 post-connection setup that your subclass may want to perform. The
4958 parameters are the same as passed to DBI->connect. If your subclass
4959 supplies a connected method, it should be part of the MySubDBI::db
4960 package.
4961
4962 One more thing to note: you must let the DBI do the handle creation.
4963 If you want to override the connect() method in your *::dr class then
4964 it must still call SUPER::connect to get a $dbh to work with.
4965 Similarly, an overridden prepare() method in *::db must still call
4966 SUPER::prepare to get a $sth. If you try to create your own handles
4967 using bless() then you'll find the DBI will reject them with an "is not
4968 a DBI handle (has no magic)" error.
4969
4970 Here's a brief example of a DBI subclass. A more thorough example can
4971 be found in t/subclass.t in the DBI distribution.
4972
4973 package MySubDBI;
4974
4975 use strict;
4976
4977 use DBI;
4978 use vars qw(@ISA);
4979 @ISA = qw(DBI);
4980
4981 package MySubDBI::db;
4982 use vars qw(@ISA);
4983 @ISA = qw(DBI::db);
4984
4985 sub prepare {
4986 my ($dbh, @args) = @_;
4987 my $sth = $dbh->SUPER::prepare(@args)
4988 or return;
4989 $sth->{private_mysubdbi_info} = { foo => 'bar' };
4990 return $sth;
4991 }
4992
4993 package MySubDBI::st;
4994 use vars qw(@ISA);
4995 @ISA = qw(DBI::st);
4996
4997 sub fetch {
4998 my ($sth, @args) = @_;
4999 my $row = $sth->SUPER::fetch(@args)
5000 or return;
5001 do_something_magical_with_row_data($row)
5002 or return $sth->set_err(1234, "The magic failed", undef, "fetch");
5003 return $row;
5004 }
5005
5006 When calling a SUPER::method that returns a handle, be careful to check
5007 the return value before trying to do other things with it in your
5008 overridden method. This is especially important if you want to set a
5009 hash attribute on the handle, as Perl's autovivification will bite you
5010 by (in)conveniently creating an unblessed hashref, which your method
5011 will then return with usually baffling results later on like the error
5012 "dbih_getcom handle HASH(0xa4451a8) is not a DBI handle (has no magic".
5013 It's best to check right after the call and return undef immediately on
5014 error, just like DBI would and just like the example above.
5015
5016 If your method needs to record an error it should call the set_err()
5017 method with the error code and error string, as shown in the example
5018 above. The error code and error string will be recorded in the handle
5019 and available via "$h->err" and $DBI::errstr etc. The set_err() method
5020 always returns an undef or empty list as appropriate. Since your method
5021 should nearly always return an undef or empty list as soon as an error
5022 is detected it's handy to simply return what set_err() returns, as
5023 shown in the example above.
5024
5025 If the handle has "RaiseError", "PrintError", or "HandleError" etc. set
5026 then the set_err() method will honour them. This means that if
5027 "RaiseError" is set then set_err() won't return in the normal way but
5028 will 'throw an exception' that can be caught with an "eval" block.
5029
5030 You can stash private data into DBI handles via "$h->{private_..._*}".
5031 See the entry under "ATTRIBUTES COMMON TO ALL HANDLES" for info and
5032 important caveats.
5033
5035 The DBI has a powerful tracing mechanism built in. It enables you to
5036 see what's going on 'behind the scenes', both within the DBI and the
5037 drivers you're using.
5038
5039 Trace Settings
5040 Which details are written to the trace output is controlled by a
5041 combination of a trace level, an integer from 0 to 15, and a set of
5042 trace flags that are either on or off. Together these are known as the
5043 trace settings and are stored together in a single integer. For normal
5044 use you only need to set the trace level, and generally only to a value
5045 between 1 and 4.
5046
5047 Each handle has it's own trace settings, and so does the DBI. When you
5048 call a method the DBI merges the handles settings into its own for the
5049 duration of the call: the trace flags of the handle are OR'd into the
5050 trace flags of the DBI, and if the handle has a higher trace level then
5051 the DBI trace level is raised to match it. The previous DBI trace
5052 settings are restored when the called method returns.
5053
5054 Trace Levels
5055 Trace levels are as follows:
5056
5057 0 - Trace disabled.
5058 1 - Trace top-level DBI method calls returning with results or errors.
5059 2 - As above, adding tracing of top-level method entry with parameters.
5060 3 - As above, adding some high-level information from the driver
5061 and some internal information from the DBI.
5062 4 - As above, adding more detailed information from the driver.
5063 This is the first level to trace all the rows being fetched.
5064 5 to 15 - As above but with more and more internal information.
5065
5066 Trace level 1 is best for a simple overview of what's happening. Trace
5067 levels 2 thru 4 a good choice for general purpose tracing. Levels 5
5068 and above are best reserved for investigating a specific problem, when
5069 you need to see "inside" the driver and DBI.
5070
5071 The trace output is detailed and typically very useful. Much of the
5072 trace output is formatted using the "neat" function, so strings in the
5073 trace output may be edited and truncated by that function.
5074
5075 Trace Flags
5076 Trace flags are used to enable tracing of specific activities within
5077 the DBI and drivers. The DBI defines some trace flags and drivers can
5078 define others. DBI trace flag names begin with a capital letter and
5079 driver specific names begin with a lowercase letter, as usual.
5080
5081 Currently the DBI only defines two trace flags:
5082
5083 ALL - turn on all DBI and driver flags (not recommended)
5084 SQL - trace SQL statements executed
5085 (not yet implemented in DBI but implemented in some DBDs)
5086
5087 The "parse_trace_flags" and "parse_trace_flag" methods are used to
5088 convert trace flag names into the corresponding integer bit flags.
5089
5090 Enabling Trace
5091 The "$h->trace" method sets the trace settings for a handle and
5092 "DBI->trace" does the same for the DBI.
5093
5094 In addition to the "trace" method, you can enable the same trace
5095 information, and direct the output to a file, by setting the
5096 "DBI_TRACE" environment variable before starting Perl. See "DBI_TRACE"
5097 for more information.
5098
5099 Finally, you can set, or get, the trace settings for a handle using the
5100 "TraceLevel" attribute.
5101
5102 All of those methods use parse_trace_flags() and so allow you set both
5103 the trace level and multiple trace flags by using a string containing
5104 the trace level and/or flag names separated by vertical bar (""|"") or
5105 comma ("","") characters. For example:
5106
5107 local $h->{TraceLevel} = "3|SQL|foo";
5108
5109 Trace Output
5110 Initially trace output is written to "STDERR". Both the "$h->trace"
5111 and "DBI->trace" methods take an optional $trace_file parameter, which
5112 may be either the name of a file to be opened by DBI in append mode, or
5113 a reference to an existing writable (possibly layered) filehandle. If
5114 $trace_file is a filename, and can be opened in append mode, or
5115 $trace_file is a writable filehandle, then all trace output (currently
5116 including that from other handles) is redirected to that file. A
5117 warning is generated if $trace_file can't be opened or is not writable.
5118
5119 Further calls to trace() without $trace_file do not alter where the
5120 trace output is sent. If $trace_file is undefined, then trace output is
5121 sent to "STDERR" and, if the prior trace was opened with $trace_file as
5122 a filename, the previous trace file is closed; if $trace_file was a
5123 filehandle, the filehandle is not closed.
5124
5125 NOTE: If $trace_file is specified as a filehandle, the filehandle
5126 should not be closed until all DBI operations are completed, or the
5127 application has reset the trace file via another call to "trace()" that
5128 changes the trace file.
5129
5130 Tracing to Layered Filehandles
5131 NOTE:
5132
5133 · Tied filehandles are not currently supported, as tie operations are
5134 not available to the PerlIO methods used by the DBI.
5135
5136 · PerlIO layer support requires Perl version 5.8 or higher.
5137
5138 As of version 5.8, Perl provides the ability to layer various
5139 "disciplines" on an open filehandle via the PerlIO module.
5140
5141 A simple example of using PerlIO layers is to use a scalar as the
5142 output:
5143
5144 my $scalar = '';
5145 open( my $fh, "+>:scalar", \$scalar );
5146 $dbh->trace( 2, $fh );
5147
5148 Now all trace output is simply appended to $scalar.
5149
5150 A more complex application of tracing to a layered filehandle is the
5151 use of a custom layer (Refer to Perlio::via for details on creating
5152 custom PerlIO layers.). Consider an application with the following
5153 logger module:
5154
5155 package MyFancyLogger;
5156
5157 sub new
5158 {
5159 my $self = {};
5160 my $fh;
5161 open $fh, '>', 'fancylog.log';
5162 $self->{_fh} = $fh;
5163 $self->{_buf} = '';
5164 return bless $self, shift;
5165 }
5166
5167 sub log
5168 {
5169 my $self = shift;
5170 return unless exists $self->{_fh};
5171 my $fh = $self->{_fh};
5172 $self->{_buf} .= shift;
5173 #
5174 # DBI feeds us pieces at a time, so accumulate a complete line
5175 # before outputing
5176 #
5177 print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and
5178 $self->{_buf} = ''
5179 if $self->{_buf}=~tr/\n//;
5180 }
5181
5182 sub close {
5183 my $self = shift;
5184 return unless exists $self->{_fh};
5185 my $fh = $self->{_fh};
5186 print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and
5187 $self->{_buf} = ''
5188 if $self->{_buf};
5189 close $fh;
5190 delete $self->{_fh};
5191 }
5192
5193 1;
5194
5195 To redirect DBI traces to this logger requires creating a package for
5196 the layer:
5197
5198 package PerlIO::via::MyFancyLogLayer;
5199
5200 sub PUSHED
5201 {
5202 my ($class,$mode,$fh) = @_;
5203 my $logger;
5204 return bless \$logger,$class;
5205 }
5206
5207 sub OPEN {
5208 my ($self, $path, $mode, $fh) = @_;
5209 #
5210 # $path is actually our logger object
5211 #
5212 $$self = $path;
5213 return 1;
5214 }
5215
5216 sub WRITE
5217 {
5218 my ($self, $buf, $fh) = @_;
5219 $$self->log($buf);
5220 return length($buf);
5221 }
5222
5223 sub CLOSE {
5224 my $self = shift;
5225 $$self->close();
5226 return 0;
5227 }
5228
5229 1;
5230
5231 The application can then cause DBI traces to be routed to the logger
5232 using
5233
5234 use PerlIO::via::MyFancyLogLayer;
5235
5236 open my $fh, '>:via(MyFancyLogLayer)', MyFancyLogger->new();
5237
5238 $dbh->trace('SQL', $fh);
5239
5240 Now all trace output will be processed by MyFancyLogger's log() method.
5241
5242 Trace Content
5243 Many of the values embedded in trace output are formatted using the
5244 neat() utility function. This means they may be quoted, sanitized, and
5245 possibly truncated if longer than $DBI::neat_maxlen. See "neat" for
5246 more details.
5247
5248 Tracing Tips
5249 You can add tracing to your own application code using the "trace_msg"
5250 method.
5251
5252 It can sometimes be handy to compare trace files from two different
5253 runs of the same script. However using a tool like "diff" on the
5254 original log output doesn't work well because the trace file is full of
5255 object addresses that may differ on each run.
5256
5257 The DBI includes a handy utility called dbilogstrip that can be used to
5258 'normalize' the log content. It can be used as a filter like this:
5259
5260 DBI_TRACE=2 perl yourscript.pl ...args1... 2>&1 | dbilogstrip > dbitrace1.log
5261 DBI_TRACE=2 perl yourscript.pl ...args2... 2>&1 | dbilogstrip > dbitrace2.log
5262 diff -u dbitrace1.log dbitrace2.log
5263
5264 See dbilogstrip for more information.
5265
5267 The DBI module recognizes a number of environment variables, but most
5268 of them should not be used most of the time. It is better to be
5269 explicit about what you are doing to avoid the need for environment
5270 variables, especially in a web serving system where web servers are
5271 stingy about which environment variables are available.
5272
5273 DBI_DSN
5274 The DBI_DSN environment variable is used by DBI->connect if you do not
5275 specify a data source when you issue the connect. It should have a
5276 format such as "dbi:Driver:databasename".
5277
5278 DBI_DRIVER
5279 The DBI_DRIVER environment variable is used to fill in the database
5280 driver name in DBI->connect if the data source string starts "dbi::"
5281 (thereby omitting the driver). If DBI_DSN omits the driver name,
5282 DBI_DRIVER can fill the gap.
5283
5284 DBI_AUTOPROXY
5285 The DBI_AUTOPROXY environment variable takes a string value that starts
5286 "dbi:Proxy:" and is typically followed by "hostname=...;port=...". It
5287 is used to alter the behaviour of DBI->connect. For full details, see
5288 DBI::Proxy documentation.
5289
5290 DBI_USER
5291 The DBI_USER environment variable takes a string value that is used as
5292 the user name if the DBI->connect call is given undef (as distinct from
5293 an empty string) as the username argument. Be wary of the security
5294 implications of using this.
5295
5296 DBI_PASS
5297 The DBI_PASS environment variable takes a string value that is used as
5298 the password if the DBI->connect call is given undef (as distinct from
5299 an empty string) as the password argument. Be extra wary of the
5300 security implications of using this.
5301
5302 DBI_DBNAME (obsolete)
5303 The DBI_DBNAME environment variable takes a string value that is used
5304 only when the obsolescent style of DBI->connect (with driver name as
5305 fourth parameter) is used, and when no value is provided for the first
5306 (database name) argument.
5307
5308 DBI_TRACE
5309 The DBI_TRACE environment variable specifies the global default trace
5310 settings for the DBI at startup. Can also be used to direct trace
5311 output to a file. When the DBI is loaded it does:
5312
5313 DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE};
5314
5315 So if "DBI_TRACE" contains an ""="" character then what follows it is
5316 used as the name of the file to append the trace to.
5317
5318 output appended to that file. If the name begins with a number followed
5319 by an equal sign ("="), then the number and the equal sign are stripped
5320 off from the name, and the number is used to set the trace level. For
5321 example:
5322
5323 DBI_TRACE=1=dbitrace.log perl your_test_script.pl
5324
5325 On Unix-like systems using a Bourne-like shell, you can do this easily
5326 on the command line:
5327
5328 DBI_TRACE=2 perl your_test_script.pl
5329
5330 See "TRACING" for more information.
5331
5332 PERL_DBI_DEBUG (obsolete)
5333 An old variable that should no longer be used; equivalent to DBI_TRACE.
5334
5335 DBI_PROFILE
5336 The DBI_PROFILE environment variable can be used to enable profiling of
5337 DBI method calls. See DBI::Profile for more information.
5338
5339 DBI_PUREPERL
5340 The DBI_PUREPERL environment variable can be used to enable the use of
5341 DBI::PurePerl. See DBI::PurePerl for more information.
5342
5344 Fatal Errors
5345 Can't call method "prepare" without a package or object reference
5346 The $dbh handle you're using to call "prepare" is probably
5347 undefined because the preceding "connect" failed. You should always
5348 check the return status of DBI methods, or use the "RaiseError"
5349 attribute.
5350
5351 Can't call method "execute" without a package or object reference
5352 The $sth handle you're using to call "execute" is probably
5353 undefined because the preceding "prepare" failed. You should always
5354 check the return status of DBI methods, or use the "RaiseError"
5355 attribute.
5356
5357 DBI/DBD internal version mismatch
5358 The DBD driver module was built with a different version of DBI
5359 than the one currently being used. You should rebuild the DBD
5360 module under the current version of DBI.
5361
5362 (Some rare platforms require "static linking". On those platforms,
5363 there may be an old DBI or DBD driver version actually embedded in
5364 the Perl executable being used.)
5365
5366 DBD driver has not implemented the AutoCommit attribute
5367 The DBD driver implementation is incomplete. Consult the author.
5368
5369 Can't [sg]et %s->{%s}: unrecognised attribute
5370 You attempted to set or get an unknown attribute of a handle. Make
5371 sure you have spelled the attribute name correctly; case is
5372 significant (e.g., "Autocommit" is not the same as "AutoCommit").
5373
5375 A pure-perl emulation of the DBI is included in the distribution for
5376 people using pure-perl drivers who, for whatever reason, can't install
5377 the compiled DBI. See DBI::PurePerl.
5378
5380 Driver and Database Documentation
5381 Refer to the documentation for the DBD driver that you are using.
5382
5383 Refer to the SQL Language Reference Manual for the database engine that
5384 you are using.
5385
5386 ODBC and SQL/CLI Standards Reference Information
5387 More detailed information about the semantics of certain DBI methods
5388 that are based on ODBC and SQL/CLI standards is available on-line via
5389 microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI standard:
5390
5391 DBI method ODBC function SQL/CLI Working Draft
5392 ---------- ------------- ---------------------
5393 column_info SQLColumns Page 124
5394 foreign_key_info SQLForeignKeys Page 163
5395 get_info SQLGetInfo Page 214
5396 primary_key_info SQLPrimaryKeys Page 254
5397 table_info SQLTables Page 294
5398 type_info SQLGetTypeInfo Page 239
5399 statistics_info SQLStatistics
5400
5401 For example, for ODBC information on SQLColumns you'd visit:
5402
5403 http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp
5404
5405 If that URL ceases to work then use the MSDN search facility at:
5406
5407 http://search.microsoft.com/us/dev/
5408
5409 and search for "SQLColumns returns" using the exact phrase option. The
5410 link you want will probably just be called "SQLColumns" and will be
5411 part of the Data Access SDK.
5412
5413 And for SQL/CLI standard information on SQLColumns you'd read page 124
5414 of the (very large) SQL/CLI Working Draft available from:
5415
5416 http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf
5417
5418 Standards Reference Information
5419 A hyperlinked, browsable version of the BNF syntax for SQL92 (plus
5420 Oracle 7 SQL and PL/SQL) is available here:
5421
5422 http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html
5423
5424 A BNF syntax for SQL3 is available here:
5425
5426 http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf
5427
5428 The following links provide further useful information about SQL. Some
5429 of these are rather dated now but may still be useful.
5430
5431 http://www.jcc.com/SQLPages/jccs_sql.htm
5432 http://www.contrib.andrew.cmu.edu/~shadow/sql.html
5433 http://www.altavista.com/query?q=sql+tutorial
5434
5435 Books and Articles
5436 Programming the Perl DBI, by Alligator Descartes and Tim Bunce.
5437 <http://books.perl.org/book/154>
5438
5439 Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant.
5440 <http://books.perl.org/book/134>
5441
5442 Learning Perl by Randal Schwartz. <http://books.perl.org/book/101>
5443
5444 Details of many other books related to perl can be found at
5445 <http://books.perl.org>
5446
5447 Perl Modules
5448 Index of DBI related modules available from CPAN:
5449
5450 http://search.cpan.org/search?mode=module&query=DBIx%3A%3A
5451 http://search.cpan.org/search?mode=doc&query=DBI
5452
5453 For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers
5454 (including Class::DBI, Alzabo, and DBIx::RecordSet in the former
5455 category and Tangram and SPOPS in the latter) see the Perl Object-
5456 Oriented Persistence project pages at:
5457
5458 http://poop.sourceforge.net
5459
5460 A similar page for Java toolkits can be found at:
5461
5462 http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison
5463
5464 Mailing List
5465 The dbi-users mailing list is the primary means of communication among
5466 users of the DBI and its related modules. For details send email to:
5467
5468 dbi-users-help@perl.org
5469
5470 There are typically between 700 and 900 messages per month. You have
5471 to subscribe in order to be able to post. However you can opt for a
5472 'post-only' subscription.
5473
5474 Mailing list archives (of variable quality) are held at:
5475
5476 http://groups.google.com/groups?group=perl.dbi.users
5477 http://www.xray.mpe.mpg.de/mailing-lists/dbi/
5478 http://www.mail-archive.com/dbi-users%40perl.org/
5479
5480 Assorted Related WWW Links
5481 The DBI "Home Page":
5482
5483 http://dbi.perl.org/
5484
5485 Other DBI related links:
5486
5487 http://tegan.deltanet.com/~phlip/DBUIdoc.html
5488 http://dc.pm.org/perl_db.html
5489 http://wdvl.com/Authoring/DB/Intro/toc.html
5490 http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html
5491 http://bumppo.net/lists/macperl/1999/06/msg00197.html
5492 http://gmax.oltrelinux.com/dbirecipes.html
5493
5494 Other database related links:
5495
5496 http://www.jcc.com/sql_stnd.html
5497 http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
5498 http://www.connectionstrings.com/
5499
5500 Security, especially the "SQL Injection" attack:
5501
5502 http://www.ngssoftware.com/research/papers.html
5503 http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
5504 http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf
5505 http://www.esecurityplanet.com/trends/article.php/2243461
5506 http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf
5507 http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html
5508 http://online.securityfocus.com/infocus/1644
5509
5510 Commercial and Data Warehouse Links
5511
5512 http://www.dwinfocenter.org
5513 http://www.datawarehouse.com
5514 http://www.datamining.org
5515 http://www.olapcouncil.org
5516 http://www.idwa.org
5517 http://www.knowledgecenters.org/dwcenter.asp
5518
5519 Recommended Perl Programming Links
5520
5521 http://language.perl.com/style/
5522
5523 FAQ
5524 See <http://faq.dbi-support.com/>
5525
5527 DBI by Tim Bunce, <http://www.tim.bunce.name>
5528
5529 This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and
5530 others. Perl by Larry Wall and the "perl5-porters".
5531
5533 The DBI module is Copyright (c) 1994-2009 Tim Bunce. Ireland. All
5534 rights reserved.
5535
5536 You may distribute under the terms of either the GNU General Public
5537 License or the Artistic License, as specified in the Perl 5.10.0 README
5538 file.
5539
5541 The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY
5542 KIND.
5543
5544 Support
5545 My consulting company, Data Plan Services, offers annual and multi-
5546 annual support contracts for the DBI. These provide sustained support
5547 for DBI development, and sustained value for you in return. Contact me
5548 for details.
5549
5550 Sponsor Enhancements
5551 The DBI Roadmap is available at
5552 <http://search.cpan.org/~timb/DBI/Roadmap.pod>
5553
5554 If your company would benefit from a specific new DBI feature, please
5555 consider sponsoring its development. Work is performed rapidly, and
5556 usually on a fixed-price payment-on-delivery basis. Contact me for
5557 details.
5558
5559 Using such targeted financing allows you to contribute to DBI
5560 development, and rapidly get something specific and valuable in return.
5561
5563 I would like to acknowledge the valuable contributions of the many
5564 people I have worked with on the DBI project, especially in the early
5565 years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti,
5566 Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael
5567 Peppler, Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander,
5568 Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson,
5569 Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen,
5570 Steve Baumgarten, Randal Schwartz, and a whole lot more.
5571
5572 Then, of course, there are the poor souls who have struggled through
5573 untold and undocumented obstacles to actually implement DBI drivers.
5574 Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan
5575 Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo,
5576 Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve
5577 Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would
5578 not be the practical reality it is today. I'm also especially grateful
5579 to Alligator Descartes for starting work on the first edition of the
5580 "Programming the Perl DBI" book and letting me jump on board.
5581
5582 The DBI and DBD::Oracle were originally developed while I was Technical
5583 Director (CTO) of Ingeneering in the UK (<http://www.ig.co.uk>)
5584 (formerly known as the Paul Ingram Group). So I'd especially like to
5585 thank Paul for his generosity and vision in supporting this work for
5586 many years.
5587
5588 A couple of specific DBI features have been sponsored by enlightened
5589 companies:
5590
5591 The development of the swap_inner_handle() method was sponsored by
5592 BizRate.com (<http://BizRate.com>)
5593
5594 The development of DBD::Gofer and related modules was sponsored by
5595 Shopzilla.com (<http://Shopzilla.com>), where I currently work.
5596
5598 As you can see above, many people have contributed to the DBI and
5599 drivers in many ways over many years.
5600
5601 If you'd like to help then see <http://dbi.perl.org/contributing> and
5602 <http://search.cpan.org/~timb/DBI/Roadmap.pod>
5603
5604 If you'd like the DBI to do something new or different then a good way
5605 to make that happen is to do it yourself and send me a patch to the
5606 source code that shows the changes. (But read "Speak before you patch"
5607 below.)
5608
5609 Browsing the source code repository
5610 Use http://svn.perl.org/modules/dbi/trunk (basic) or
5611 http://svn.perl.org/viewcvs/modules/ (more useful)
5612
5613 How to create a patch using Subversion
5614 The DBI source code is maintained using Subversion (a replacement for
5615 CVS, see <http://subversion.tigris.org/>). To access the source you'll
5616 need to install a Subversion client. Then, to get the source code, do:
5617
5618 svn checkout http://svn.perl.org/modules/dbi/trunk
5619
5620 If it prompts for a username and password use your perl.org account if
5621 you have one, else just 'guest' and 'guest'. The source code will be in
5622 a new subdirectory called "trunk".
5623
5624 To keep informed about changes to the source you can send an empty
5625 email to svn-commit-modules-dbi-subscribe@perl.org after which you'll
5626 get an email with the change log message and diff of each change
5627 checked-in to the source.
5628
5629 After making your changes you can generate a patch file, but before you
5630 do, make sure your source is still up to date using:
5631
5632 svn update
5633
5634 If you get any conflicts reported you'll need to fix them first. Then
5635 generate the patch file from within the "trunk" directory using:
5636
5637 svn diff > foo.patch
5638
5639 Read the patch file, as a sanity check, and then email it to
5640 dbi-dev@perl.org.
5641
5642 How to create a patch without Subversion
5643 Unpack a fresh copy of the distribution:
5644
5645 tar xfz DBI-1.40.tar.gz
5646
5647 Rename the newly created top level directory:
5648
5649 mv DBI-1.40 DBI-1.40.your_foo
5650
5651 Edit the contents of DBI-1.40.your_foo/* till it does what you want.
5652
5653 Test your changes and then remove all temporary files:
5654
5655 make test && make distclean
5656
5657 Go back to the directory you originally unpacked the distribution:
5658
5659 cd ..
5660
5661 Unpack another copy of the original distribution you started with:
5662
5663 tar xfz DBI-1.40.tar.gz
5664
5665 Then create a patch file by performing a recursive "diff" on the two
5666 top level directories:
5667
5668 diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch
5669
5670 Speak before you patch
5671 For anything non-trivial or possibly controversial it's a good idea to
5672 discuss (on dbi-dev@perl.org) the changes you propose before actually
5673 spending time working on them. Otherwise you run the risk of them being
5674 rejected because they don't fit into some larger plans you may not be
5675 aware of.
5676
5678 A German translation of this manual (possibly slightly out of date) is
5679 available, thanks to O'Reilly, at:
5680
5681 http://www.oreilly.de/catalog/perldbiger/
5682
5683 Some other translations:
5684
5685 http://cronopio.net/perl/ - Spanish
5686 http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese
5687
5689 References to DBI related training resources. No recommendation
5690 implied.
5691
5692 http://www.treepax.co.uk/
5693 http://www.keller.com/dbweb/
5694
5695 (If you offer professional DBI related training services, please send
5696 me your details so I can add them here.)
5697
5699 Apache::DBI by E.Mergl@bawue.de
5700 To be used with the Apache daemon together with an embedded Perl
5701 interpreter like "mod_perl". Establishes a database connection
5702 which remains open for the lifetime of the HTTP daemon. This way
5703 the CGI connect and disconnect for every database access becomes
5704 superfluous.
5705
5706 SQL Parser
5707 See also the SQL::Statement module, SQL parser and engine.
5708
5709
5710
5711perl v5.10.1 2009-06-05 DBI(3)