Repository navigation
Expand file tree
/
Copy pathDBI.html
More file actions
5061 lines (3191 loc) · 309 KB
/
Copy pathDBI.html
File metadata and controls
5061 lines (3191 loc) · 309 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
7
10BC8
6
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DBI - Database independent interface for Perl</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:hmbrand@cpan.org" />
</head>
<body>
<ul id="index">
<li><a href="#NAME">NAME</a></li>
<li><a href="#SYNOPSIS">SYNOPSIS</a>
<ul>
<li><a href="#GETTING-HELP">GETTING HELP</a>
<ul>
<li><a href="#General">General</a></li>
<li><a href="#Mailing-Lists">Mailing Lists</a></li>
<li><a href="#IRC">IRC</a></li>
<li><a href="#Online">Online</a></li>
<li><a href="#Reporting-a-Bug">Reporting a Bug</a></li>
</ul>
</li>
<li><a href="#NOTES">NOTES</a></li>
</ul>
</li>
<li><a href="#DESCRIPTION">DESCRIPTION</a>
<ul>
<li><a href="#Architecture-of-a-DBI-Application">Architecture of a DBI Application</a></li>
<li><a href="#Notation-and-Conventions">Notation and Conventions</a></li>
<li><a href="#Outline-Usage">Outline Usage</a></li>
<li><a href="#General-Interface-Rules-Caveats">General Interface Rules & Caveats</a></li>
<li><a href="#Naming-Conventions-and-Name-Space">Naming Conventions and Name Space</a></li>
<li><a href="#SQL---A-Query-Language">SQL - A Query Language</a></li>
<li><a href="#Placeholders-and-Bind-Values">Placeholders and Bind Values</a></li>
</ul>
</li>
<li><a href="#THE-DBI-PACKAGE-AND-CLASS">THE DBI PACKAGE AND CLASS</a>
<ul>
<li><a href="#DBI-Constants">DBI Constants</a></li>
<li><a href="#DBI-Class-Methods">DBI Class Methods</a>
<ul>
<li><a href="#parse_dsn">parse_dsn</a></li>
<li><a href="#connect">connect</a></li>
<li><a href="#connect_cached">connect_cached</a></li>
<li><a href="#available_drivers">available_drivers</a></li>
<li><a href="#installed_drivers">installed_drivers</a></li>
<li><a href="#installed_versions">installed_versions</a></li>
<li><a href="#data_sources">data_sources</a></li>
<li><a href="#trace">trace</a></li>
<li><a href="#visit_handles">visit_handles</a></li>
</ul>
</li>
<li><a href="#DBI-Utility-Functions">DBI Utility Functions</a>
<ul>
<li><a href="#data_string_desc">data_string_desc</a></li>
<li><a href="#data_string_diff">data_string_diff</a></li>
<li><a href="#data_diff">data_diff</a></li>
<li><a href="#neat">neat</a></li>
<li><a href="#neat_list">neat_list</a></li>
<li><a href="#looks_like_number">looks_like_number</a></li>
<li><a href="#hash">hash</a></li>
<li><a href="#sql_type_cast">sql_type_cast</a></li>
</ul>
</li>
<li><a href="#DBI-Dynamic-Attributes">DBI Dynamic Attributes</a>
<ul>
<li><a href="#DBI%3A%3Aerr">$DBI::err</a></li>
<li><a href="#DBI%3A%3Aerrstr">$DBI::errstr</a></li>
<li><a href="#DBI%3A%3Astate">$DBI::state</a></li>
<li><a href="#DBI%3A%3Arows">$DBI::rows</a></li>
<li><a href="#DBI%3A%3Alasth">$DBI::lasth</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#METHODS-COMMON-TO-ALL-HANDLES">METHODS COMMON TO ALL HANDLES</a>
<ul>
<li>
<ul>
<li><a href="#err">err</a></li>
<li><a href="#errstr">errstr</a></li>
<li><a href="#state">state</a></li>
<li><a href="#set_err">set_err</a></li>
<li><a href="#trace1">trace</a></li>
<li><a href="#trace_msg">trace_msg</a></li>
<li><a href="#func">func</a></li>
<li><a href="#can">can</a></li>
<li><a href="#parse_trace_flags">parse_trace_flags</a></li>
<li><a href="#parse_trace_flag">parse_trace_flag</a></li>
<li><a href="#private_attribute_info">private_attribute_info</a></li>
<li><a href="#swap_inner_handle">swap_inner_handle</a></li>
<li><a href="#visit_child_handles">visit_child_handles</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#ATTRIBUTES-COMMON-TO-ALL-HANDLES">ATTRIBUTES COMMON TO ALL HANDLES</a>
<ul>
<li>
<ul>
<li><a href="#Warn">Warn</a></li>
<li><a href="#Active">Active</a></li>
<li><a href="#Executed">Executed</a></li>
<li><a href="#Kids">Kids</a></li>
<li><a href="#ActiveKids">ActiveKids</a></li>
<li><a href="#CachedKids">CachedKids</a></li>
<li><a href="#Type">Type</a></li>
<li><a href="#ChildHandles">ChildHandles</a></li>
<li><a href="#CompatMode">CompatMode</a></li>
<li><a href="#InactiveDestroy">InactiveDestroy</a></li>
<li><a href="#AutoInactiveDestroy">AutoInactiveDestroy</a></li>
<li><a href="#PrintWarn">PrintWarn</a></li>
<li><a href="#PrintError">PrintError</a></li>
<li><a href="#RaiseWarn">RaiseWarn</a></li>
<li><a href="#RaiseError">RaiseError</a></li>
<li><a href="#HandleError">HandleError</a></li>
<li><a href="#HandleSetErr">HandleSetErr</a></li>
<li><a href="#ErrCount">ErrCount</a></li>
<li><a href="#ShowErrorStatement">ShowErrorStatement</a></li>
<li><a href="#TraceLevel">TraceLevel</a></li>
<li><a href="#FetchHashKeyName">FetchHashKeyName</a></li>
<li><a href="#ChopBlanks">ChopBlanks</a></li>
<li><a href="#LongReadLen">LongReadLen</a></li>
<li><a href="#LongTruncOk">LongTruncOk</a></li>
<li><a href="#TaintIn">TaintIn</a></li>
<li><a href="#TaintOut">TaintOut</a></li>
<li><a href="#Taint">Taint</a></li>
<li><a href="#Profile">Profile</a></li>
<li><a href="#ReadOnly">ReadOnly</a></li>
<li><a href="#Callbacks">Callbacks</a></li>
<li><a href="#private_your_module_name_&q
10BC8
uot;>private_your_module_name_*</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#DBI-DATABASE-HANDLE-OBJECTS">DBI DATABASE HANDLE OBJECTS</a>
<ul>
<li><a href="#Database-Handle-Methods">Database Handle Methods</a>
<ul>
<li><a href="#clone">clone</a></li>
<li><a href="#data_sources1">data_sources</a></li>
<li><a href="#do">do</a></li>
<li><a href="#last_insert_id">last_insert_id</a></li>
<li><a href="#selectrow_array">selectrow_array</a></li>
<li><a href="#selectrow_arrayref">selectrow_arrayref</a></li>
<li><a href="#selectrow_hashref">selectrow_hashref</a></li>
<li><a href="#selectall_arrayref">selectall_arrayref</a></li>
<li><a href="#selectall_array">selectall_array</a></li>
<li><a href="#selectall_hashref">selectall_hashref</a></li>
<li><a href="#selectcol_arrayref">selectcol_arrayref</a></li>
<li><a href="#prepare">prepare</a></li>
<li><a href="#prepare_cached">prepare_cached</a></li>
<li><a href="#commit">commit</a></li>
<li><a href="#rollback">rollback</a></li>
<li><a href="#begin_work">begin_work</a></li>
<li><a href="#disconnect">disconnect</a></li>
<li><a href="#ping">ping</a></li>
<li><a href="#get_info">get_info</a></li>
<li><a href="#table_info">table_info</a></li>
<li><a href="#column_info">column_info</a></li>
<li><a href="#primary_key_info">primary_key_info</a></li>
<li><a href="#primary_key">primary_key</a></li>
<li><a href="#foreign_key_info">foreign_key_info</a></li>
<li><a href="#statistics_info">statistics_info</a></li>
<li><a href="#tables">tables</a></li>
<li><a href="#type_info_all">type_info_all</a></li>
<li><a href="#type_info">type_info</a></li>
<li><a href="#quote">quote</a></li>
<li><a href="#quote_identifier">quote_identifier</a></li>
<li><a href="#take_imp_data">take_imp_data</a></li>
</ul>
</li>
<li><a href="#Database-Handle-Attributes">Database Handle Attributes</a>
<ul>
<li><a href="#AutoCommit">AutoCommit</a></li>
<li><a href="#Driver">Driver</a></li>
<li><a href="#Name">Name</a></li>
<li><a href="#Statement">Statement</a></li>
<li><a href="#RowCacheSize">RowCacheSize</a></li>
<li><a href="#Username">Username</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#DBI-STATEMENT-HANDLE-OBJECTS">DBI STATEMENT HANDLE OBJECTS</a>
<ul>
<li><a href="#Statement-Handle-Methods">Statement Handle Methods</a>
<ul>
<li><a href="#bind_param">bind_param</a></li>
<li><a href="#bind_param_inout">bind_param_inout</a></li>
<li><a href="#bind_param_array">bind_param_array</a></li>
<li><a href="#execute">execute</a></li>
<li><a href="#execute_array">execute_array</a></li>
<li><a href="#execute_for_fetch">execute_for_fetch</a></li>
<li><a href="#last_insert_id1">last_insert_id</a></li>
<li><a href="#fetchrow_arrayref">fetchrow_arrayref</a></li>
<li><a href="#fetchrow_array">fetchrow_array</a></li>
<li><a href="#fetchrow_hashref">fetchrow_hashref</a></li>
<li><a href="#fetchall_arrayref">fetchall_arrayref</a></li>
<li><a href="#fetchall_hashref">fetchall_hashref</a></li>
<li><a href="#more_results">more_results</a></li>
<li><a href="#finish">finish</a></li>
<li><a href="#rows">rows</a></li>
<li><a href="#bind_col">bind_col</a></li>
<li><a href="#bind_columns">bind_columns</a></li>
<li><a href="#dump_results">dump_results</a></li>
</ul>
</li>
<li><a href="#Statement-Handle-Attributes">Statement Handle Attributes</a>
<ul>
<li><a href="#NUM_OF_FIELDS">NUM_OF_FIELDS</a></li>
<li><a href="#NUM_OF_PARAMS">NUM_OF_PARAMS</a></li>
<li><a href="#NAME1">NAME</a></li>
<li><a href="#NAME_lc">NAME_lc</a></li>
<li><a href="#NAME_uc">NAME_uc</a></li>
<li><a href="#NAME_hash">NAME_hash</a></li>
<li><a href="#NAME_lc_hash">NAME_lc_hash</a></li>
<li><a href="#NAME_uc_hash">NAME_uc_hash</a></li>
<li><a href="#TYPE">TYPE</a></li>
<li><a href="#PRECISION">PRECISION</a></li>
<li><a href="#SCALE">SCALE</a></li>
<li><a href="#NULLABLE">NULLABLE</a></li>
<li><a href="#CursorName">CursorName</a></li>
<li><a href="#Database">Database</a></li>
<li><a href="#Statement1">Statement</a></li>
<li><a href="#ParamValues">ParamValues</a></li>
<li><a href="#ParamTypes">ParamTypes</a></li>
<li><a href="#ParamArrays">ParamArrays</a></li>
<li><a href="#RowsInCache">RowsInCache</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#FURTHER-INFORMATION">FURTHER INFORMATION</a>
<ul>
<li><a href="#Catalog-Methods">Catalog Methods</a></li>
<li><a href="#Transactions">Transactions</a></li>
<li><a href="#Handling-BLOB-LONG-Memo-Fields">Handling BLOB / LONG / Memo Fields</a></li>
<li><a href="#Simple-Examples">Simple Examples</a></li>
<li><a href="#Threads-and-Thread-Safety">Threads and Thread Safety</a></li>
<li><a href="#Signal-Handling-and-Canceling-Operations">Signal Handling and Canceling Operations</a></li>
<li><a href="#Subclassing-the-DBI">Subclassing the DBI</a></li>
<li><a href="#Memory-Leaks">Memory Leaks</a></li>
</ul>
</li>
<li><a href="#TRACING">TRACING</a>
<ul>
<li><a href="#Trace-Settings">Trace Settings</a></li>
<li><a href="#Trace-Levels">Trace Levels</a></li>
<li><a href="#Trace-Flags">Trace Flags</a></li>
<li><a href="#Enabling-Trace">Enabling Trace</a></li>
<li><a href="#Trace-Output">Trace Output</a></li>
<li><a href="#Tracing-to-Layered-Filehandles">Tracing to Layered Filehandles</a></li>
<li><a href="#Trace-Content">Trace Content</a></li>
<li><a href="#Tracing-Tips">Tracing Tips</a></li>
</ul>
</li>
<li><a href="#DBI-ENVIRONMENT-VARIABLES">DBI ENVIRONMENT VARIABLES</a>
<ul>
<li><a href="#DBI_DSN">DBI_DSN</a></li>
<li><a href="#DBI_DRIVER">DBI_DRIVER</a></li>
<li><a href="#DBI_AUTOPROXY">DBI_AUTOPROXY</a></li>
<li><a href="#DBI_USER">DBI_USER</a></li>
<li><a href="#DBI_PASS">DBI_PASS</a></li>
<li><a href="#DBI_DBNAME-obsolete">DBI_DBNAME (obsolete)</a></li>
<li><a href="#DBI_TRACE">DBI_TRACE</a></li>
<li><a href="#PERL_DBI_DEBUG-obsolete">PERL_DBI_DEBUG (obsolete)</a></li>
<li><a href="#DBI_PROFILE">DBI_PROFILE</a></li>
<li><a href="#DBI_PUREPERL">DBI_PUREPERL</a></li>
</ul>
</li>
<li><a href="#WARNING-AND-ERROR-MESSAGES">WARNING AND ERROR MESSAGES</a>
<ul>
<li><a href="#Fatal-Errors">Fatal Errors</a></li>
</ul>
</li>
<li><a href="#Pure-Perl-DBI">Pure-Perl DBI</a></li>
<li><a href="#SEE-ALSO">SEE ALSO</a>
<ul>
<li><a href="#Driver-and-Database-Documentation">Driver and Database Documentation</a></li>
<li><a href="#ODBC-and-SQL-CLI-Standards-Reference-Information">ODBC and SQL/CLI Standards Reference Information</a></li>
<li><a href="#Standards-Reference-Information">Standards Reference Information</a></li>
<li><a href="#Books-and-Articles">Books and Articles</a></li>
<li><a href="#Perl-Modules">Perl Modules</a></li>
<li><a href="#Mailing-List">Mailing List</a></li>
<li><a href="#Assorted-Related-Links">Assorted Related Links</a></li>
<li><a href="#FAQ">FAQ</a></li>
</ul>
</li>
<li><a href="#AUTHORS">AUTHORS</a></li>
<li><a href="#COPYRIGHT">COPYRIGHT</a></li>
<li><a href="#SUPPORT-WARRANTY">SUPPORT / WARRANTY</a>
<ul>
<li><a href="#Support">Support</a></li>
<li><a href="#Sponsor-Enhancements">Sponsor Enhancements</a></li>
</ul>
</li>
<li><a href="#ACKNOWLEDGEMENTS">ACKNOWLEDGEMENTS</a></li>
<li><a href="#CONTRIBUTING">CONTRIBUTING</a>
<ul>
<li><a href="#Browsing-the-source-code-repository">Browsing the source code repository</a></li>
<li><a href="#How-to-create-a-patch-using-Git">How to create a patch using Git</a></li>
<li><a href="#How-to-create-a-patch-without-Git">How to create a patch without Git</a></li>
<li><a href="#Speak-before-you-patch">Speak before you patch</a></li>
</ul>
</li>
<li><a href="#TRANSLATIONS">TRANSLATIONS</a></li>
<li><a href="#OTHER-RELATED-WORK-AND-PERL-MODULES">OTHER RELATED WORK AND PERL MODULES</a></li>
<li><a href="#TODO">TODO</a>
<ul>
<li><a href="#Documentation">Documentation</a></li>
</ul>
</li>
</ul>
<h1 id="NAME">NAME</h1>
<p>DBI - Database independent interface for Perl</p>
<h1 id="SYNOPSIS">SYNOPSIS</h1>
<pre><code>use DBI;
@driver_names = DBI->available_drivers;
%drivers = DBI->installed_drivers;
@data_sources = DBI->data_sources($driver_name, \%attr);
$dbh = DBI->connect($data_source, $username, $auth, \%attr);
$rv = $dbh->do($statement);
$rv = $dbh->do($statement, \%attr);
$rv = $dbh->do($statement, \%attr, @bind_values);
$ary_ref = $dbh->selectall_arrayref($statement);
$hash_ref = $dbh->selectall_hashref($statement, $key_field);
$ary_ref = $dbh->selectcol_arrayref($statement);
$ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
@row_ary = $dbh->selectrow_array($statement);
$ary_ref = $dbh->selectrow_arrayref($statement);
$hash_ref = $dbh->selectrow_hashref($statement);
$sth = $dbh->prepare($statement);
$sth = $dbh->prepare_cached($statement);
$rc = $sth->bind_param($p_num, $bind_value);
$rc = $sth->bind_param($p_num, $bind_value, $bind_type);
$rc = $sth->bind_param($p_num, $bind_value, \%attr);
$rv = $sth->execute;
$rv = $sth->execute(@bind_values);
$rv = $sth->execute_array(\%attr, ...);
$rc = $sth->bind_col($col_num, \$col_variable);
$rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
@row_ary = $sth->fetchrow_array;
$ary_ref = $sth->fetchrow_arrayref;
$hash_ref = $sth->fetchrow_hashref;
$ary_ref = $sth->fetchall_arrayref;
$ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
$hash_ref = $sth->fetchall_hashref( $key_field );
$rv = $sth->rows;
$rc = $dbh->begin_work;
$rc = $dbh->commit;
$rc = $dbh->rollback;
$quoted_string = $dbh->quote($string);
$rc = $h->err;
$str = $h->errstr;
$rv = $h->state;
$rc = $dbh->disconnect;</code></pre>
<p><i>The synopsis above only lists the major methods and parameters.</i></p>
<h2 id="GETTING-HELP">GETTING HELP</h2>
<h3 id="General">General</h3>
<p>Before asking any questions, reread this document, consult the archives and read the DBI FAQ. The archives are listed at the end of this document and on the DBI home page <a href="http://dbi.perl.org/support/">http://dbi.perl.org/support/</a></p>
<p>You might also like to read the Advanced DBI Tutorial at <a href="http://www.slideshare.net/Tim.Bunce/dbi-advanced-tutorial-2007">http://www.slideshare.net/Tim.Bunce/dbi-advanced-tutorial-2007</a></p>
<p>To help you make the best use of the dbi-users mailing list, and any other lists or forums you may use, I recommend that you read "Getting Answers" by Mike Ash: <a href="http://mikeash.com/getting_answers.html">http://mikeash.com/getting_answers.html</a>.</p>
<h3 id="Mailing-Lists">Mailing Lists</h3>
<p>If you have questions about DBI, or DBD driver modules, you can get help from the <i>dbi-users@perl.org</i> mailing list. This is the best way to get help. You don't have to subscribe to the list in order to post, though I'd recommend it. You can get help on subscribing and using the list by emailing <i>dbi-users-help@perl.org</i>.</p>
<p>Please note that Tim Bunce does not maintain the mailing lists or the web pages (generous volunteers do that). So please don't send mail directly to him; he just doesn't have the time to answer questions personally. The <i>dbi-users</i> mailing list has lots of experienced people who should be able to help you if you need it. If you do email Tim he is very likely to just forward it to the mailing list.</p>
<h3 id="IRC">IRC</h3>
<p>DBI IRC Channel: #dbi on irc.perl.org (<a href="irc://irc.perl.org/#dbi">irc://irc.perl.org/#dbi</a>)</p>
<a href="http://chat.mibbit.com/#dbi@irc.perl.org">(click for instant chatroom login)</a>
<h3 id="Online">Online</h3>
<p>StackOverflow has a DBI tag <a href="https://stackoverflow.com/questions/tagged/dbi">https://stackoverflow.com/questions/tagged/dbi</a> with over 800 questions.</p>
<p>The DBI home page at <a href="https://dbi.perl.org/">https://dbi.perl.org/</a> might be worth a visit. It includes links to other resources, but <i>is rather out-dated</i>.</p>
<h3 id="Reporting-a-Bug">Reporting a Bug</h3>
<p>If you think you've found a bug then please read "How to Report Bugs Effectively" by Simon Tatham: <a href="https://www.chiark.greenend.org.uk/~sgtatham/bugs.html">https://www.chiark.greenend.org.uk/~sgtatham/bugs.html</a>.</p>
<p>If you think you've found a memory leak then read <a href="#Memory-Leaks">"Memory Leaks"</a>.</p>
<p>Your problem is most likely related to the specific DBD driver module you're using. If that's the case then click on the 'Bugs' link on the <a href="https://metacpan.org">https://metacpan.org</a> page for your driver. Only submit a bug report against the DBI itself if you're sure that your issue isn't related to the driver you're using.</p>
<h2 id="NOTES">NOTES</h2>
<p>This is the DBI specification that corresponds to DBI version 1.653 (see <a>DBI::Changes</a> for details).</p>
<p>The DBI is evolving at a steady pace, so it's good to check that you have the latest copy.</p>
<p>The significant user-visible changes in each release are documented in the <a>DBI::Changes</a> module so you can read them by executing <code>perldoc DBI::Changes</code>.</p>
<p>Some DBI changes require changes in the drivers, but the drivers can take some time to catch up. Newer versions of the DBI have added features that may not yet be supported by the drivers you use. Talk to the authors of your drivers if you need a new feature that is not yet supported.</p>
<p>Features added after DBI 1.21 (February 2002) are marked in the text with the version number of the DBI release they first appeared in.</p>
<p>Extensions to the DBI API often use the <code>DBIx::*</code> namespace. See <a href="#Naming-Conventions-and-Name-Space">"Naming Conventions and Name Space"</a>. DBI extension modules can be found at <a href="https://metacpan.org/search?q=DBIx">https://metacpan.org/search?q=DBIx</a>. And all modules related to the DBI can be found at <a href="https://metacpan.org/search?q=DBI">https://metacpan.org/search?q=DBI</a>.</p>
<h1 id="DESCRIPTION">DESCRIPTION</h1>
<p>The DBI is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.</p>
<p>It is important to remember that the DBI is just an interface. The DBI is a layer of "glue" between an application and one or more database <i>driver</i> modules. It is the driver modules which do most of the real work. The DBI provides a standard interface and framework for the drivers to operate within.</p>
<p>This document often uses terms like <i>references</i>, <i>objects</i>, <i>methods</i>. If you're not familiar with those terms then it would be a good idea to read at least the following perl manuals first: <a>perlreftut</a>, <a>perldsc</a>, <a>perllol</a>, and <a>perlboot</a>.</p>
<h2 id="Architecture-of-a-DBI-Application">Architecture of a DBI Application</h2>
<pre><code> |<- Scope of DBI ->|
.-. .--------------. .-------------.
.-------. | |---| XYZ Driver |---| XYZ Engine |
| Perl | | | `--------------' `-------------'
| script| |A| |D| .--------------. .-------------.
| using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
| DBI | |I| |I| `--------------' `-------------'
| API | | |...
|methods| | |... Other drivers
`-------' | |...
`-'</code></pre>
<p>The API, or Application Programming Interface, defines the call interface and variables for Perl scripts to use. The API is implemented by the Perl DBI extension.</p>
<p>The DBI "dispatches" the method calls to the appropriate driver for actual execution. The DBI is also responsible for the dynamic loading of drivers, error checking and handling, providing default implementations for methods, and many other non-database specific duties.</p>
<p>Each driver contains implementations of the DBI methods using the private interface functions of the corresponding database engine. Only authors of sophisticated/multi-database applications or generic library functions need be concerned with drivers.</p>
<h2 id="Notation-and-Conventions">Notation and Conventions</h2>
<p>The following conventions are used in this document:</p>
<pre><code>$dbh Database handle object
$sth Statement handle object
$drh Driver handle object (rarely seen or used in applications)
$h Any of the handle types above ($dbh, $sth, or $drh)
$rc General Return Code (boolean: true=ok, false=error)
$rv General Return Value (typically an integer)
@ary List of values returned from the database, typically a row of data
$rows Number of rows processed (if available, else -1)
$fh A filehandle
undef NULL values are represented by undefined values in Perl
\%attr Reference to a hash of attribute values passed to methods</code></pre>
<p>Note that Perl will automatically destroy database and statement handle objects if all references to them are deleted.</p>
<h2 id="Outline-Usage">Outline Usage</h2>
<p>To use DBI, first you need to load the DBI module:</p>
<pre><code>use DBI;
use strict;</code></pre>
<p>(The <code>use strict;</code> isn't required but is strongly recommended.)</p>
<p>Then you need to <a href="#connect">"connect"</a> to your data source and get a <i>handle</i> for that connection:</p>
<pre><code>$dbh = DBI->connect($dsn, $user, $password,
{ RaiseError => 1, AutoCommit => 0 });</code></pre>
<p>Since connecting can be expensive, you generally just connect at the start of your program and disconnect at the end.</p>
<p>Explicitly defining the required <code>AutoCommit</code> behaviour is strongly recommended and may become mandatory in a later version. This determines whether changes are automatically committed to the database when executed, or need to be explicitly committed later.</p>
<p>The DBI allows an application to "prepare" statements for later execution. A prepared statement is identified by a statement handle held in a Perl variable. We'll call the Perl variable <code>$sth</code> in our examples.</p>
<p>The typical method call sequence for a <code>SELECT</code> statement is:</p>
<pre><code>prepare,
execute, fetch, fetch, ...
execute, fetch, fetch, ...
execute, fetch, fetch, ...</code></pre>
<p>for example:</p>
<pre><code>$sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
$sth->execute( $baz );
while ( @row = $sth->fetchrow_array ) {
print "@row\n";
}</code></pre>
<p>For queries that are not executed many times at once, it is often cleaner to use the higher level select wrappers:</p>
<pre><code>$row_hashref = $dbh->selectrow_hashref("SELECT foo, bar FROM table WHERE baz=?", undef, $baz);
$arrayref_of_row_hashrefs = $dbh->selectall_arrayref(
"SELECT foo, bar FROM table WHERE baz BETWEEN ? AND ?",
{ Slice => {} }, $baz_min, $baz_max);</code></pre>
<p>The typical method call sequence for a <i>non</i>-<code>SELECT</code> statement is:</p>
<pre><code>prepare,
execute,
execute,
execute.</code></pre>
<p>for example:</p>
<pre><code>$sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
while(<CSV>) {
chomp;
my ($foo,$bar,$baz) = split /,/;
$sth->execute( $foo, $bar, $baz );
}</code></pre>
<p>The <code>do()</code> method is a wrapper of prepare and execute that can be simpler for non repeated <i>non</i>-<code>SELECT</code> statements (or with drivers that don't support placeholders):</p>
<pre><code>$rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
$rows_affected = $dbh->do("DELETE FROM table WHERE foo = ?", undef, $foo);</code></pre>
<p>To commit your changes to the database (when <a href="#AutoCommit">"AutoCommit"</a> is off):</p>
<pre><code>$dbh->commit; # or call $dbh->rollback; to undo changes</code></pre>
<p>Finally, when you have finished working with the data source, you should <a href="#disconnect">"disconnect"</a> from it:</p>
<pre><code>$dbh->disconnect;</code></pre>
<h2 id="General-Interface-Rules-Caveats">General Interface Rules & Caveats</h2>
<p>The DBI does not have a concept of a "current session". Every session has a handle object (i.e., a <code>$dbh</code>) returned from the <code>connect</code> method. That handle object is used to invoke database related methods.</p>
<p>Most data is returned to the Perl script as strings. (Null values are returned as <code>undef</code>.) This allows arbitrary precision numeric data to be handled without loss of accuracy. Beware that Perl may not preserve the same accuracy when the string is used as a number.</p>
<p>Dates and times are returned as character strings in the current default format of the corresponding database engine. Time zone effects are database/driver dependent.</p>
<p>Perl supports binary data in Perl strings, and the DBI will pass binary data to and from the driver without change. It is up to the driver implementors to decide how they wish to handle such binary data.</p>
<p>Perl supports two kinds of strings: Unicode (utf8 internally) and non-Unicode (defaults to iso-8859-1 if forced to assume an encoding). Drivers should accept both kinds of strings and, if required, convert them to the character set of the database being used. Similarly, when fetching from the database character data that isn't iso-8859-1 the driver should convert it into utf8.</p>
<p>Multiple SQL statements may not be combined in a single statement handle (<code>$sth</code>), although some databases and drivers do support this (notably Sybase and SQL Server).</p>
<p>Non-sequential record reads are not supported in this version of the DBI. In other words, records can only be fetched in the order that the database returned them, and once fetched they are forgotten.</p>
<p>Positioned updates and deletes are not directly supported by the DBI. See the description of the <code>CursorName</code> attribute for an alternative.</p>
<p>Individual driver implementors are free to provide any private functions and/or handle attributes that they feel are useful. Private driver functions can be invoked using the DBI <code>func()</code> method. Private driver attributes are accessed just like standard attributes.</p>
<p>Many methods have an optional <code>\%attr</code> parameter which can be used to pass information to the driver implementing the method. Except where specifically documented, the <code>\%attr</code> parameter can only be used to pass driver specific hints. In general, you can ignore <code>\%attr</code> parameters or pass it as <code>undef</code>.</p>
<h2 id="Naming-Conventions-and-Name-Space">Naming Conventions and Name Space</h2>
<p>The DBI package and all packages below it (<code>DBI::*</code>) are reserved for use by the DBI. Extensions and related modules use the <code>DBIx::</code> namespace (see <a href="http://www.perl.com/CPAN/modules/by-module/DBIx/">http://www.perl.com/CPAN/modules/by-module/DBIx/</a>). Package names beginning with <code>DBD::</code> are reserved for use by DBI database drivers. All environment variables used by the DBI or by individual DBDs begin with "<code>DBI_</code>" or "<code>DBD_</code>".</p>
<p>The letter case used for attribute names is significant and plays an important part in the portability of DBI scripts. The case of the attribute name is used to signify who defined the meaning of that name and its values.</p>
<pre><code>Case of name Has a meaning defined by
------------ ------------------------
UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable)
MixedCase DBI API (portable), underscores are not used.
lower_case Driver or database engine specific (non-portable)</code></pre>
<p>It is of the utmost importance that Driver developers only use lowercase attribute names when defining private attributes. Private attribute names must be prefixed with the driver name or suitable abbreviation (e.g., "<code>ora_</code>" for Oracle, "<code>ing_</code>" for Ingres, etc).</p>
<h2 id="SQL---A-Query-Language">SQL - A Query Language</h2>
<p>Most DBI drivers require applications to use a dialect of SQL (Structured Query Language) to interact with the database engine. The <a href="#Standards-Reference-Information">"Standards Reference Information"</a> section provides links to useful information about SQL.</p>
<p>The DBI itself does not mandate or require any particular language to be used; it is language independent. In ODBC terms, the DBI is in "pass-thru" mode, although individual drivers might not be. The only requirement is that queries and other statements must be expressed as a single string of characters passed as the first argument to the <a href="#prepare">"prepare"</a> or <a href="#do">"do"</a> methods.</p>
<p>For an interesting diversion on the <i>real</i> history of RDBMS and SQL, from the people who made it happen, see:</p>
<pre><code>http://www.mcjones.org/System_R/SQL_Reunion_95/sqlr95.html</code></pre>
<p>Follow the "Full Contents" then "Intergalactic dataspeak" links for the SQL history.</p>
<h2 id="Placeholders-and-Bind-Values">Placeholders and Bind Values</h2>
<p>Some drivers support placeholders and bind values. <i>Placeholders</i>, also called parameter markers, are used to indicate values in a database statement that will be supplied later, before the prepared statement is executed. For example, an application might use the following to insert a row of data into the SALES table:</p>
<pre><code>INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)</code></pre>
<p>or the following, to select the description for a product:</p>
<pre><code>SELECT description FROM products WHERE product_code = ?</code></pre>
<p>The <code>?</code> characters are the placeholders. The association of actual values with placeholders is known as <i>binding</i>, and the values are referred to as <i>bind values</i>. Note that the <code>?</code> is not enclosed in quotation marks, even when the placeholder represents a string.</p>
<p>Some drivers also allow placeholders like <code>:</code><i>name</i> and <code>:</code><i>N</i> (e.g., <code>:1</code>, <code>:2</code>, and so on) in addition to <code>?</code>, but their use is not portable.</p>
<p>If the <code>:</code><i>N</i> form of placeholder is supported by the driver you're using, then you should be able to use either <a href="#bind_param">"bind_param"</a> or <a href="#execute">"execute"</a> to bind values. Check your driver documentation.</p>
<p>Some drivers allow you to prevent the recognition of a placeholder by placing a single backslash character (<code>\</code>) immediately before it. The driver will remove the backslash character and ignore the placeholder, passing it unchanged to the backend. If the driver supports this then <a href="#get_info">"get_info"</a>(9000) will return true.</p>
<p>With most drivers, placeholders can't be used for any element of a statement that would prevent the database server from validating the statement and creating a query execution plan for it. For example:</p>
<pre><code>"SELECT name, age FROM ?" # wrong (will probably fail)
"SELECT name, ? FROM people" # wrong (but may not 'fail')</code></pre>
<p>Also, placeholders can only represent single scalar values. For example, the following statement won't work as expected for more than one value:</p>
<pre><code>"SELECT name, age FROM people WHERE name IN (?)" # wrong
"SELECT name, age FROM people WHERE name IN (?,?)" # two names</code></pre>
<p>When using placeholders with the SQL <code>LIKE</code> qualifier, you must remember that the placeholder substitutes for the whole string. So you should use "<code>... LIKE ? ...</code>" and include any wildcard characters in the value that you bind to the placeholder.</p>
<p><b>NULL Values</b></p>
<p>Undefined values, or <code>undef</code>, are used to indicate NULL values. You can insert and update columns with a NULL value as you would a non-NULL value. These examples insert and update the column <code>age</code> with a NULL value:</p>
<pre><code>$sth = $dbh->prepare(qq{
INSERT INTO people (fullname, age) VALUES (?, ?)
});
$sth->execute("Joe Bloggs", undef);
$sth = $dbh->prepare(qq{
UPDATE people SET age = ? WHERE fullname = ?
});
$sth->execute(undef, "Joe Bloggs");</code></pre>
<p>However, care must be taken when trying to use NULL values in a <code>WHERE</code> clause. Consider:</p>
<pre><code>SELECT fullname FROM people WHERE age = ?</code></pre>
<p>Binding an <code>undef</code> (NULL) to the placeholder will <i>not</i> select rows which have a NULL <code>age</code>! At least for database engines that conform to the SQL standard. Refer to the SQL manual for your database engine or any SQL book for the reasons for this. To explicitly select NULLs you have to say "<code>WHERE age IS NULL</code>".</p>
<p>A common issue is to have a code fragment handle a value that could be either <code>defined</code> or <code>undef</code> (non-NULL or NULL) at runtime. A simple technique is to prepare the appropriate statement as needed, and substitute the placeholder for non-NULL cases:</p>
<pre><code>$sql_clause = defined $age? "age = ?" : "age IS NULL";
$sth = $dbh->prepare(qq{
SELECT fullname FROM people WHERE $sql_clause
});
$sth->execute(defined $age ? $age : ());</code></pre>
<p>The following technique illustrates qualifying a <code>WHERE</code> clause with several columns, whose associated values (<code>defined</code> or <code>undef</code>) are in a hash %h:</p>
<pre><code>for my $col ("age", "phone", "email") {
if (defined $h{$col}) {
push @sql_qual, "$col = ?";
push @sql_bind, $h{$col};
}
else {
push @sql_qual, "$col IS NULL";
}
}
$sql_clause = join(" AND ", @sql_qual);
$sth = $dbh->prepare(qq{
SELECT fullname FROM people WHERE $sql_clause
});
$sth->execute(@sql_bind);</code></pre>
<p>The techniques above call prepare for the SQL statement with each call to execute. Because calls to prepare() can be expensive, performance can suffer when an application iterates many times over statements like the above.</p>
<p>A better solution is a single <code>WHERE</code> clause that supports both NULL and non-NULL comparisons. Its SQL statement would need to be prepared only once for all cases, thus improving performance. Several examples of <code>WHERE</code> clauses that support this are presented below. But each example lacks portability, robustness, or simplicity. Whether an example is supported on your database engine depends on what SQL extensions it provides, and where it supports the <code>?</code> placeholder in a statement.</p>
<pre><code>0) age = ?
1) NVL(age, xx) = NVL(?, xx)
2) ISNULL(age, xx) = ISNULL(?, xx)
3) DECODE(age, ?, 1, 0) = 1
4) age = ? OR (age IS NULL AND ? IS NULL)
5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1)
6) age = ? OR (age IS NULL AND ? = 1)</code></pre>
<p>Statements formed with the above <code>WHERE</code> clauses require execute statements as follows. The arguments are required, whether their values are <code>defined</code> or <code>undef</code>.</p>
<pre><code>0,1,2,3) $sth->execute($age);
4,5) $sth->execute($age, $age);
6) $sth->execute($age, defined($age) ? 0 : 1);</code></pre>
<p>Example 0 should not work (as mentioned earlier), but may work on a few database engines anyway (e.g. Sybase). Example 0 is part of examples 4, 5, and 6, so if example 0 works, these other examples may work, even if the engine does not properly support the right hand side of the <code>OR</code> expression.</p>
<p>Examples 1 and 2 are not robust: they require that you provide a valid column value xx (e.g. '~') which is not present in any row. That means you must have some notion of what data won't be stored in the column, and expect clients to adhere to that.</p>
<p>Example 5 requires that you provide a stored procedure (SP_ISNULL in this example) that acts as a function: it checks whether a value is null, and returns 1 if it is, or 0 if not.</p>
<p>Example 6, the least simple, is probably the most portable, i.e., it should work with most, if not all, database engines.</p>
<p>Here is a table that indicates which examples above are known to work on various database engines:</p>
<pre><code> -----Examples------
0 1 2 3 4 5 6
- - - - - - -
Oracle 9 N Y N Y Y ? Y
Informix IDS 9 N N N Y N Y Y
MS SQL N N Y N Y ? Y
Sybase Y N N N N N Y
AnyData,DBM,CSV Y N N N Y Y* Y
SQLite 3.3 N N N N Y N N
MSAccess N N N N Y N Y</code></pre>
<p>* Works only because Example 0 works.</p>
<p>DBI provides a sample perl script that will test the examples above on your database engine and tell you which ones work. It is located in the <i>ex/</i> subdirectory of the DBI source distribution, or here: <a href="https://github.com/perl5-dbi/dbi/blob/master/ex/perl_dbi_nulls_test.pl">https://github.com/perl5-dbi/dbi/blob/master/ex/perl_dbi_nulls_test.pl</a> Please use the script to help us fill-in and maintain this table.</p>
<p><b>Performance</b></p>
<p>Without using placeholders, the insert statement shown previously would have to contain the literal values to be inserted and would have to be re-prepared and re-executed for each row. With placeholders, the insert statement only needs to be prepared once. The bind values for each row can be given to the <code>execute</code> method each time it's called. By avoiding the need to re-prepare the statement for each row, the application typically runs many times faster. Here's an example:</p>
<pre><code>my $sth = $dbh->prepare(q{
INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
}) or die $dbh->errstr;
while (<>) {
chomp;
my ($product_code, $qty, $price) = split /,/;
$sth->execute($product_code, $qty, $price) or die $dbh->errstr;
}
$dbh->commit or die $dbh->errstr;</code></pre>
<p>See <a href="#execute">"execute"</a> and <a href="#bind_param">"bind_param"</a> for more details.</p>
<p>The <code>q{...}</code> style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote like <code>qq{...}</code> operator if you want to interpolate variables into the string. See <a>"Quote and Quote-like Operators" in perlop</a> for more details.</p>
<p>See also the <a href="#bind_columns">"bind_columns"</a> method, which is used to associate Perl variables with the output columns of a <code>SELECT</code> statement.</p>
<h1 id="THE-DBI-PACKAGE-AND-CLASS">THE DBI PACKAGE AND CLASS</h1>
<p>In this section, we cover the DBI class methods, utility functions, and the dynamic attributes associated with generic DBI handles.</p>
<h2 id="DBI-Constants">DBI Constants</h2>
<p>Constants representing the values of the SQL standard types can be imported individually by name, or all together by importing the special <code>:sql_types</code> tag.</p>
<p>The names and values of all the defined SQL standard types can be produced like this:</p>
<pre><code>foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) {
printf "%s=%d\n", $_, &{"DBI::$_"};
}</code></pre>
<p>These constants are defined by SQL/CLI, ODBC or both. <code>SQL_BIGINT</code> has conflicting codes in SQL/CLI and ODBC, DBI uses the ODBC one.</p>
<p>See the <a href="#type_info">"type_info"</a>, <a href="#type_info_all">"type_info_all"</a>, and <a href="#bind_param">"bind_param"</a> methods for possible uses.</p>
<p>Note that just because the DBI defines a named constant for a given data type doesn't mean that drivers will support that data type.</p>
<h2 id="DBI-Class-Methods">DBI Class Methods</h2>
<p>The following methods are provided by the DBI class:</p>
<h3 id="parse_dsn"><code>parse_dsn</code></h3>
<pre><code>($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn)
or die "Can't parse DBI DSN '$dsn'";</code></pre>
<p>Breaks apart a DBI Data Source Name (DSN) and returns the individual parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns an empty list.</p>
<p>$scheme is the first part of the DSN and is currently always 'dbi'. $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER}, and may be undefined. $attr_string is the contents of the optional attribute string, which may be undefined. If $attr_string is not empty then $attr_hash is a reference to a hash containing the parsed attribute names and values. $driver_dsn is the last part of the DBI DSN string. For example:</p>
<pre><code>($scheme, $driver, $attr_string, $attr_hash, $driver_dsn)
= DBI->parse_dsn("dbi:MyDriver(RaiseError=>1):db=test;port=42");
$scheme = 'dbi';
$driver = 'MyDriver';
$attr_string = 'RaiseError=>1';
$attr_hash = { 'RaiseError' => '1' };
$driver_dsn = 'db=test;port=42';</code></pre>
<p>The parse_dsn() method was added in DBI 1.43.</p>
<h3 id="connect"><code>connect</code></h3>
<pre><code>$dbh = DBI->connect($data_source, $username, $password)
or die $DBI::errstr;
$dbh = DBI->connect($data_source, $username, $password, \%attr)
or die $DBI::errstr;</code></pre>
<p>Establishes a database connection, or session, to the requested <code>$data_source</code>. Returns a database handle object if the connection succeeds. Use <code>$dbh->disconnect</code> to terminate the connection.</p>
<p>If the connect fails (see below), it returns <code>undef</code> and sets both <code>$DBI::err</code> and <code>$DBI::errstr</code>. (It does <i>not</i> explicitly set <code>$!</code>.) You should generally test the return status of <code>connect</code> and <code>print $DBI::errstr</code> if it has failed.</p>
<p>Multiple simultaneous connections to multiple databases through multiple drivers can be made via the DBI. Simply make one <code>connect</code> call for each database and keep a copy of each returned database handle.</p>
<p>The <code>$data_source</code> value must begin with "<code>dbi:</code><i>driver_name</i><code>:</code>". The <i>driver_name</i> specifies the driver that will be used to make the connection. (Letter case is significant.)</p>
<p>As a convenience, if the <code>$data_source</code> parameter is undefined or empty, the DBI will substitute the value of the environment variable <code>DBI_DSN</code>. If just the <i>driver_name</i> part is empty (i.e., the <code>$data_source</code> prefix is "<code>dbi::</code>"), the environment variable <code>DBI_DRIVER</code> is used. If neither variable is set, then <code>connect</code> dies.</p>
<p>Examples of <code>$data_source</code> values are:</p>
<pre><code>dbi:DriverName:database_name
dbi:DriverName:database_name@hostname:port
dbi:DriverName:database=database_name;host=hostname;port=port</code></pre>
<p>There is <i>no standard</i> for the text following the driver name. Each driver is free to use whatever syntax it wants. The only requirement the DBI makes is that all the information is supplied in a single string. You must consult the documentation for the drivers you are using for a description of the syntax they require.</p>
<p>It is recommended that drivers support the ODBC style, shown in the last example above. It is also recommended that they support the three common names '<code>host</code>', '<code>port</code>', and '<code>database</code>' (plus '<code>db</code>' as an alias for <code>database</code>). This simplifies automatic construction of basic DSNs: <code>"dbi:$driver:database=$db;host=$host;port=$port"</code>. Drivers should aim to 'do something reasonable' when given a DSN in this form, but if any part is meaningless for that driver (such as 'port' for Informix) it should generate an error if that part is not empty.</p>
<p>If the environment variable <code>DBI_AUTOPROXY</code> is defined (and the driver in <code>$data_source</code> is not "<code>Proxy</code>") then the connect request will automatically be changed to:</p>
<pre><code>$ENV{DBI_AUTOPROXY};dsn=$data_source</code></pre>
<p><code>DBI_AUTOPROXY</code> is typically set as "<code>dbi:Proxy:hostname=...;port=...</code>". If $ENV{DBI_AUTOPROXY} doesn't begin with '<code>dbi:</code>' then "dbi:Proxy:" will be prepended to it first. See the DBD::Proxy documentation for more details.</p>
<p>If <code>$
10BC8
username</code> or <code>$password</code> are undefined (rather than just empty), then the DBI will substitute the values of the <code>DBI_USER</code> and <code>DBI_PASS</code> environment variables, respectively. The DBI will warn if the environment variables are not defined. However, the everyday use of these environment variables is not recommended for security reasons. The mechanism is primarily intended to simplify testing. See below for alternative way to specify the username and password.</p>
<p><code>DBI->connect</code> automatically installs the driver if it has not been installed yet. Driver installation either returns a valid driver handle, or it <i>dies</i> with an error message that includes the string "<code>install_driver</code>" and the underlying problem. So <code>DBI->connect</code> will die on a driver installation failure and will only return <code>undef</code> on a connect failure, in which case <code>$DBI::errstr</code> will hold the error message. Use <code>eval</code> if you need to catch the "<code>install_driver</code>" error.</p>
<p>The <code>$data_source</code> argument (with the "<code>dbi:...:</code>" prefix removed) and the <code>$username</code> and <code>$password</code> arguments are then passed to the driver for processing. The DBI does not define any interpretation for the contents of these fields. The driver is free to interpret the <code>$data_source</code>, <code>$username</code>, and <code>$password</code> fields in any way, and supply whatever defaults are appropriate for the engine being accessed. (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment variables if no <code>$data_source</code> is specified.)</p>
<p>The <code>AutoCommit</code> and <code>PrintError</code> attributes for each connection default to "on". (See <a href="#AutoCommit">"AutoCommit"</a> and <a href="#PrintError">"PrintError"</a> for more information.) However, it is strongly recommended that you explicitly define <code>AutoCommit</code> rather than rely on the default. The <code>PrintWarn</code> attribute defaults to true. The <code>RaiseWarn</code> attribute defaults to false.</p>
<p>The <code>\%attr</code> parameter can be used to alter the default settings of <code>PrintError</code>, <code>RaiseError</code>, <code>AutoCommit</code>, and other attributes. For example:</p>
<pre><code>$dbh = DBI->connect($data_source, $user, $pass, {
PrintError => 0,
AutoCommit => 0
});</code></pre>
<p>The username and password can also be specified using the attributes <code>Username</code> and <code>Password</code>, in which case they take precedence over the <code>$username</code> and <code>$password</code> parameters.</p>
<p>You can also define connection attribute values within the <code>$data_source</code> parameter. For example:</p>
<pre><code>dbi:DriverName(PrintWarn=>0,PrintError=>0,Taint=>1):...</code></pre>
<p>Individual attributes values specified in this way take precedence over any conflicting values specified via the <code>\%attr</code> parameter to <code>connect</code>.</p>
<p>The <code>dbi_connect_method</code> attribute can be used to specify which driver method should be called to establish the connection. The only useful values are 'connect', 'connect_cached', or some specialized case like 'Apache::DBI::connect' (which is automatically the default when running within Apache).</p>
<p>Where possible, each session (<code>$dbh</code>) is independent from the transactions in other sessions. This is useful when you need to hold cursors open across transactions--for example, if you use one session for your long lifespan cursors (typically read-only) and another for your short update transactions.</p>
<p>For compatibility with old DBI scripts, the driver can be specified by passing its name as the fourth argument to <code>connect</code> (instead of <code>\%attr</code>):</p>
<pre><code>$dbh = DBI->connect($data_source, $user, $pass, $driver);</code></pre>
<p>In this "old-style" form of <code>connect</code>, the <code>$data_source</code> should not start with "<code>dbi:driver_name:</code>". (If it does, the embedded driver_name will be ignored). Also note that in this older form of <code>connect</code>, the <code>$dbh->{AutoCommit}</code> attribute is <i>undefined</i>, the <code>$dbh->{PrintError}</code> attribute is off, and the old <code>DBI_DBNAME</code> environment variable is checked if <code>DBI_DSN</code> is not defined. Beware that this "old-style" <code>connect</code> will soon be withdrawn in a future version of DBI.</p>
<h3 id="connect_cached"><code>connect_cached</code></h3>
<pre><code>$dbh = DBI->connect_cached($data_source, $username, $password)
or die $DBI::errstr;
$dbh = DBI->connect_cached($data_source, $username, $password, \%attr)
or die $DBI::errstr;</code></pre>
<p><code>connect_cached</code> is like <a href="#connect">"connect"</a>, except that the database handle returned is also stored in a hash associated with the given parameters. If another call is made to <code>connect_cached</code> with the same parameter values, then the corresponding cached <code>$dbh</code> will be returned if it is still valid. The cached database handle is replaced with a new connection if it has been disconnected or if the <code>ping</code> method fails.</p>
<p>Note that the behaviour of this method differs in several respects from the behaviour of persistent connections implemented by Apache::DBI. However, if Apache::DBI is loaded then <code>connect_cached</code> will use it.</p>
<p>Caching connections can be useful in some applications, but it can also cause problems, such as too many connections, and so should be used with care. In particular, avoid changing the attributes of a database handle created via connect_cached() because it will affect other code that may be using the same handle. When connect_cached() returns a handle the attributes will be reset to their initial values. This can cause problems, especially with the <code>AutoCommit</code> attribute.</p>
<p>Also, to ensure that the attributes passed are always the same, avoid passing references inline. For example, the <code>Callbacks</code> attribute is specified as a hash reference. Be sure to declare it external to the call to connect_cached(), such that the hash reference is not re-created on every call. A package-level lexical works well:</p>
<pre><code>package MyDBH;
my $cb = {
'connect_cached.reused' => sub { delete $_[4]->{AutoCommit} },
};
sub dbh {
DBI->connect_cached( $dsn, $username, $auth, { Callbacks => $cb });
}</code></pre>
<p>Where multiple separate parts of a program are using connect_cached() to connect to the same database with the same (initial) attributes it is a good idea to add a private attribute to the connect_cached() call to effectively limit the scope of the caching. For example:</p>
<pre><code>DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... });</code></pre>
<p>Handles returned from that connect_cached() call will only be returned by other connect_cached() call elsewhere in the code if those other calls also pass in the same attribute values, including the private one. (I've used <code>private_foo_cachekey</code> here as an example, you can use any attribute name with a <code>private_</code> prefix.)</p>
<p>Taking that one step further, you can limit a particular connect_cached() call to return handles unique to that one place in the code by setting the private attribute to a unique value for that place:</p>
<pre><code>DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... });</code></pre>
<p>By using a private attribute you still get connection caching for the individual calls to connect_cached() but, by making separate database connections for separate parts of the code, the database handles are isolated from any attribute changes made to other handles.</p>
<p>The cache can be accessed (and cleared) via the <a href="#CachedKids">"CachedKids"</a> attribute:</p>
<pre><code>my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
%$CachedKids_hashref = () if $CachedKids_hashref;</code></pre>
<h3 id="available_drivers"><code>available_drivers</code></h3>
<pre><code>@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);</code></pre>
<p>Returns a list of all available drivers by searching for <code>DBD::*</code> modules through the directories in <code>@INC</code>. By default, a warning is given if some drivers are hidden by others of the same name in earlier directories. Passing a true value for <code>$quiet</code> will inhibit the warning.</p>
<h3 id="installed_drivers"><code>installed_drivers</code></h3>
<pre><code>%drivers = DBI->installed_drivers();</code></pre>
<p>Returns a list of driver name and driver handle pairs for all drivers 'installed' (loaded) into the current process. The driver name does not include the 'DBD::' prefix.</p>
<p>To get a list of all drivers available in your perl installation you can use <a href="#available_drivers">"available_drivers"</a>.</p>
<p>Added in DBI 1.49.</p>
<h3 id="installed_versions"><code>installed_versions</code></h3>
<pre><code>DBI->installed_versions;
@ary = DBI->installed_versions;
$hash = DBI->installed_versions;</code></pre>
<p>Calls available_drivers() and attempts to load each of them in turn using install_driver(). For each load that succeeds the driver name and version number are added to a hash. When running under <a>DBI::PurePerl</a> drivers which appear not be pure-perl are ignored.</p>
<p>When called in array context the list of successfully loaded drivers is returned (without the 'DBD::' prefix).</p>
<p>When called in scalar context an extra entry for the <code>DBI</code> is added (and <code>DBI::PurePerl</code> if appropriate) and a reference to the hash is returned.</p>
<p>When called in a void context the installed_versions() method will print out a formatted list of the hash contents, one per line, along with some other information about the DBI version and OS.</p>
<p>Due to the potentially high memory cost and unknown risks of loading in an unknown number of drivers that just happen to be installed on the system, this method is not recommended for general use. Use available_drivers() instead.</p>
<p>The installed_versions() method is primarily intended as a quick way to see from the command line what's installed. For example:</p>
<pre><code>perl -MDBI -e 'DBI->installed_versions'</code></pre>
<p>The installed_versions() method was added in DBI 1.38.</p>
<h3 id="data_sources"><code>data_sources</code></h3>
<pre><code>@ary = DBI->data_sources($driver);
@ary = DBI->data_sources($driver, \%attr);</code></pre>
<p>Returns a list of data sources (databases) available via the named driver. If <code>$driver</code> is empty or <code>undef</code>, then the value of the <code>DBI_DRIVER</code> environment variable is used.</p>
<p>The driver will be loaded if it hasn't been already. Note that if the driver loading fails then data_sources() <i>dies</i> with an error message that includes the string "<code>install_driver</code>" and the underlying problem.</p>
<p>Data sources are returned in a form suitable for passing to the <a href="#connect">"connect"</a> method (that is, they will include the "<code>dbi:$driver:</code>" prefix).</p>
<p>Note that many drivers have no way of knowing what data sources might be available for it. These drivers return an empty or incomplete list or may require driver-specific attributes.</p>
<p>There is also a data_sources() method defined for database handles.</p>
<h3 id="trace"><code>trace</code></h3>
<pre><code>DBI->trace($trace_setting)
DBI->trace($trace_setting, $trace_filename)
DBI->trace($trace_setting, $trace_filehandle)
$trace_setting = DBI->trace;</code></pre>
<p>The <code>DBI->trace</code> method sets the <i>global default</i> trace settings and returns the <i>previous</i> trace settings. It can also be used to change where the trace output is sent.</p>
<p>There's a similar method, <code>$h->trace</code>, which sets the trace settings for the specific handle it's called on.</p>
<p>See the <a href="#TRACING">"TRACING"</a> section for full details about the DBI's powerful tracing facilities.</p>
<h3 id="visit_handles"><code>visit_handles</code></h3>
<pre><code>DBI->visit_handles( $coderef );
DBI->visit_handles( $coderef, $info );</code></pre>
<p>Where $coderef is a reference to a subroutine and $info is an arbitrary value which, if undefined, defaults to a reference to an empty hash. Returns $info.</p>
<p>For each installed driver handle, if any, $coderef is invoked as:</p>
<pre><code>$coderef->($driver_handle, $info);</code></pre>
<p>If the execution of $coderef returns a true value then <a href="#visit_child_handles">"visit_child_handles"</a> is called on that child handle and passed the returned value as $info.</p>
<p>For example:</p>
<pre><code>my $info = $dbh->{Driver}->visit_child_handles(sub {
my ($h, $info) = @_;
++$info->{ $h->{Type} }; # count types of handles (dr/db/st)
return $info; # visit kids
});</code></pre>
<p>See also <a href="#visit_child_handles">"visit_child_handles"</a>.</p>
<h2 id="DBI-Utility-Functions">DBI Utility Functions</h2>
<p>In addition to the DBI methods listed in the previous section, the DBI package also provides several utility functions.</p>
<p>These can be imported into your code by listing them in the <code>use</code> statement. For example:</p>
<pre><code>use DBI qw(neat data_diff);</code></pre>
<p>Alternatively, all these utility functions (except hash) can be imported using the <code>:utils</code> import tag. For example:</p>
<pre><code>use DBI qw(:utils);</code></pre>
<h3 id="data_string_desc"><code>data_string_desc</code></h3>
<pre><code>$description = data_string_desc($string);</code></pre>