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