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