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