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