- 名前
- 概要
- 説明
- DBI パッケージとクラス
- 全てのハンドルに共通のメソッド
- 全てのハンドルに共通の属性
-
Warn(boolean, inherited)Active(boolean, read-only)Executed(boolean)Kids(integer, read-only)ActiveKids(integer, read-only)CachedKids(hash ref)Type(scalar, read-only)ChildHandles(array ref)CompatMode(boolean, inherited)InactiveDestroy(boolean)PrintWarn(boolean, inherited)PrintError(boolean, inherited)RaiseError(boolean, inherited)HandleError(code ref, inherited)HandleSetErr(code ref, inherited)ErrCount(unsigned integer)ShowErrorStatement(boolean, inherited)TraceLevel(integer, inherited)FetchHashKeyName(string, inherited)ChopBlanks(boolean, inherited)LongReadLen(unsigned integer, inherited)LongTruncOk(boolean, inherited)TaintIn(boolean, inherited)TaintOut(boolean, inherited)Taint(boolean, inherited)Profile(inherited)ReadOnly(boolean, inherited)Callbacks(hash ref)private_your_module_name_*
-
- DBI データベースハンドルオブジェクト
- データベースハンドルメソッド
clonedata_sourcesdolast_insert_idselectrow_arrayselectrow_arrayrefselectrow_hashrefselectall_arrayrefselectall_hashrefselectcol_arrayrefprepareprepare_cachedcommitrollbackbegin_workdisconnectpingget_infotable_infocolumn_infoprimary_key_infoprimary_keyforeign_key_infostatistics_infotablestype_info_alltype_infoquotequote_identifiertake_imp_data
- データベースハンドル属性
- データベースハンドルメソッド
- DBI 文ハンドルオブジェクト
- 文ハンドルメソッド
- 文ハンドル属性
NUM_OF_FIELDS(integer, read-only)NUM_OF_PARAMS(integer, read-only)NAME(array-ref, read-only)NAME_lc(array-ref, read-only)NAME_uc(array-ref, read-only)NAME_hash(hash-ref, read-only)NAME_lc_hash(hash-ref, read-only)NAME_uc_hash(hash-ref, read-only)TYPE(array-ref, read-only)PRECISION(array-ref, read-only)SCALE(array-ref, read-only)NULLABLE(array-ref, read-only)CursorName(string, read-only)Database(dbh, read-only)Statement(string, read-only)ParamValues(hash ref, read-only)ParamTypes(hash ref, read-only)ParamArrays(hash ref, read-only)RowsInCache(integer, read-only)
- さらなる情報
- トレース
- DBI 環境変数
- 警告とエラーメッセージ
- ピュア Perl の DBI
- SEE ALSO
- 作者
- コピーライト
- サポート / 保証
- 謝辞
- 寄与する
- 翻訳
- トレーニング
- その他の関係する作品と Perl モジュール
名前¶
DBI - Database independent interface for Perl
DBI - Perl 用データベース独立インターフェース
(訳注: (TBR)がついている段落は「みんなの自動翻訳@TexTra」による 機械翻訳です。)
概要¶
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;
The synopsis above only lists the major methods and parameters.
上記の概略は主なメソッドとパラメータだけをリストにしています。
助けを得る¶
If you have questions about DBI, or DBD driver modules, you can get help from the dbi-users@perl.org mailing list. 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 dbi-users-help@perl.org.
DBI や DBD ドライバモジュールに関する質問があるなら、 dbi-users@perl.org メーリングリストで助けを得られます。 投稿するのにメーリングリストの購読は必要ではありませんが、購読することを 勧めます。 dbi-users-help@perl.org にメールすることで、メーリングリストの購読および 使用に関する助けが得られます。
I don't recommend the DBI cpanforum (at http://www.cpanforum.com/dist/DBI) because relatively few people read it compared with dbi-users@perl.org.
私は DBI cpanforum (at http://www.cpanforum.com/dist/DBI) は勧めません; dbi-users@perl.org に比べて読んでいる人数が少ないからです。
To help you make the best use of the dbi-users mailing list, and any other lists or forums you may use, I strongly recommend that you read "How To Ask Questions The Smart Way" by Eric Raymond: http://www.catb.org/~esr/faqs/smart-questions.html.
dbi-users メーリングリストや、その他のメーリングリストやフォーラムを うまく利用するために、私は Eric Raymond による "How To Ask Questions The Smart Way" http://www.catb.org/~esr/faqs/smart-questions.html (和訳:「賢い質問のしかた」 http://www.ranvis.com/articles/smart-questions.ja.html) を 読むことを 強く 勧めます。
If you think you've found a bug then please also read "How to Report Bugs Effectively" by Simon Tatham: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html.
バグを発見したと思ったら、Simon Tatham による "How to Report Bugs Effectively" http://www.chiark.greenend.org.uk/~sgtatham/bugs.html (和訳: 「効果的にバグを報告するには」 http://www.chiark.greenend.org.uk/~sgtatham/bugs-jp.html) も 読んでください。
The DBI home page at http://dbi.perl.org/ and the DBI FAQ at http://faq.dbi-support.com/ are always worth a visit. They include links to other resources.
http://dbi.perl.org/ の DBI ホームページと http://faq.dbi-support.com/ の DBI FAQ は常に訪れる価値のある場所です。 これらには他のリソースへのリンクもあります。
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.
質問をする前に、このドキュメントを読み返し、アーカイブをあたり、DBI FAQ を 読んでください。 アーカイブはこのリストの最後と DBI ホームページに一覧があります。
This document often uses terms like references, objects, methods. If you're not familiar with those terms then it would be a good idea to read at least the following perl manuals first: perlreftut, perldsc, perllol, and perlboot.
この文書にはしばしば リファレンス, オブジェクト, メソッド といった 用語を使います。 これらの用語に親しみがないなら、少なくとも以下のマニュアルを先に読むのが いい考えです: perlreftut, perldsc, perllol, perlboot
Please note that Tim Bunce does not maintain the mailing lists or the web page (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 dbi-users 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.
Tim Bunce がそのメーリングリストや Web ページを管理しているわけでは ないことに注意してください(通常はボランティアがやっています)。 そのため彼に直接メールを送らないで下さい; 彼には個人的に質問に答える時間が ないだけです。 dbi-users メーリングリストは経験豊富な人たちがたくさんいて、必要であれば あなたを助けてくれるでしょう。 Tim にメールしても、おそらく単にメーリングリストに転送されるでしょう。
注意¶
This is the DBI specification that corresponds to the DBI version 1.612 ($Revision$).
これは DBI バージョン1.612 ($Revision$) に対応した DBI の仕様です。
The DBI is evolving at a steady pace, so it's good to check that you have the latest copy.
DBI の仕様は、現在、確実なペースで更新されています。 最新のものを持っているかをチェックしてください。
The significant user-visible changes in each release are documented in the DBI::Changes module so you can read them by executing perldoc DBI::Changes.
リリース毎のユーザーに見える重要な変更は DBI::Changes モジュールに 文書化されているので、perldoc DBI::Changes を実行することで これを読むことができます。
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.
DBI の変更によってドライバの変更が必要になる場合もありますが、 ドライバは追いつくのに少し時間がかかります。 新しいバージョンの DBI は、今使っているドライバではまだ対応していない 機能を追加していることもあります。 もしまだ対応していない新しい機能が必要なら、ドライバの作者に 話してみてください。
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.
DBI 1.21 (2002 年 2 月) 以降に追加された機能については、最初に 追加された DBI リリースのバージョン番号を文章中に記しています。
Extensions to the DBI API often use the DBIx::* namespace. See "Naming Conventions and Name Space". DBI extension modules can be found at http://search.cpan.org/search?mode=module&query=DBIx. And all modules related to the DBI can be found at http://search.cpan.org/search?query=DBI&mode=all.
DBI API のエクステンションはしばしば DBIx::* 名前空間が使われます。 "Naming Conventions and Name Space" を参照してください。 DBI エクステンションモジュールは http://search.cpan.org/search?mode=module&query=DBIx にあります。 DBI 関連の全てのモジュールは http://search.cpan.org/search?query=DBI&mode=all にあります。
説明¶
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.
DBI は Perl プログラミング言語のためのデータベースアクセスモジュールです。 それはセットになったメソッド、変数そして規約を定義し、実際の使われている データベースに依存しない一貫性のあるデータベースインターフェースを 提供します。
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 driver 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.
DBI が単なるインターフェースであることを忘れないことは重要です。 DBI はアプリケーションと一つまたは複数のデータベース ドライバ モジュールとを結び付ける薄い「糊」の層なのです。 実際に働くのはドライバモジュールです。 DBI はドライバを操作するための標準のインターフェースと枠組みを提供します。
DBI アプリケーションのアーキテクチャ¶
|<- 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
`-------' | |...
`-'
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.
API、つまりアプリケーション・プログラミング・インターフェースは Perl スクリプトが使うための呼び出しインタフェースと変数を定義します。 API は Perl DBI エクステンションによって実装されます。
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.
DBI は適切なドライバへ実際の実行のためにメソッド呼び出しを 「発行」(dispatch)します。 DBI はドライバの動的なロード、エラーのチェック/操作、メソッドのための デフォルトの実装の提供、その他たくさんのデータベース特有なこと以外にも 責任を持ちます。
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.
各ドライバは対応するデータベースエンジンのプライベートなインターフェース 関数を使い、DBI メソッドの実装を持ちます。 高度な/複数のデータベースに対応するアプリーケーションや 汎用ライブラリ関数の作成者だけが、このドライバに関心をもつ必要があります。
記法と規約¶
The following conventions are used in this document:
このドキュメントでは以下の表記法を使用します:
$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
$dbh データベースハンドルオブジェクト
$sth 文ハンドルオブジェクト
$drh ドライバハンドルオブジェクト(アプリケーションで目にしたり、使ったりすることはまずありません)
$h 上記のハンドルのどれか
$rc 一般的な戻り値(コード)(真偽値: 真=OK, 偽=エラー)
$rv 一般的な戻り値(値) (通常はinteger)
@ary データベースから返される値のリスト。通常はデータの行
$rows 処理された行の数 (もしあれば。なければ -1)
$fh ファイルハンドル
undef Perl では NULL値は未定義値で表現される
\%attr メソッドに渡される属性値のハッシュのリファレンス
Note that Perl will automatically destroy database and statement handle objects if all references to them are deleted.
注意:そこへの参照がすべて削除されると、Perl は、自動的にデータベースと ステートメントオブジェクトを破壊します。
使用法の概要¶
To use DBI, first you need to load the DBI module:
DBI を使うためには、まず DBI モジュールをロードする必要があります:
use DBI;
use strict;
(The use strict; isn't required but is strongly recommended.)
(use strict; は必須ではありませんが、強く推奨します。)
Then you need to "connect" to your data source and get a handle for that connection:
そしてデータソースに接続("connect")し、その接続のための ハンドル を取得します:
$dbh = DBI->connect($dsn, $user, $password,
{ RaiseError => 1, AutoCommit => 0 });
Since connecting can be expensive, you generally just connect at the start of your program and disconnect at the end.
接続にはコストがかかるので、一般的にはプログラムの開始した時点で接続し、 終わりで切断します:
Explicitly defining the required AutoCommit 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.
要求される AutoCommit の動きを明示的に定義することは強く推奨されます。 将来のバージョンでは必須になるかもしれません。 これは実行したときに変更を自動的にデータベースにコミットするか、後から 明示的にコミットされる必要があるかを決定します。
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 $sth in our examples.
DBI では、アプリケーションはSQL文を後で実行するための "prepare"(=準備)をしておくことができます。 prepare された文は Perl 変数に入った文ハンドルにより 識別されます。 この例ではその Perl 変数を $sth とします。
The typical method call sequence for a SELECT statement is:
SELECT 文のための典型的なメソッドの順番は以下のようになります:
prepare,
execute, fetch, fetch, ...
execute, fetch, fetch, ...
execute, fetch, fetch, ...
for example:
例:
$sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
$sth->execute( $baz );
while ( @row = $sth->fetchrow_array ) {
print "@row\n";
}
The typical method call sequence for a non-SELECT statement is:
SELECT 文 以外 のための典型的なメソッドの順番は 以下のようになります:
prepare,
execute,
execute,
execute.
for example:
例:
$sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
while(<CSV>) {
chomp;
my ($foo,$bar,$baz) = split /,/;
$sth->execute( $foo, $bar, $baz );
}
The do() method can be used for non repeated non-SELECT statement (or with drivers that don't support placeholders):
do() メソッドは繰り返されない SELECT 以外 の文のために (またはプレースホルダをサポートしないドライバで)使うことができます:
$rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
To commit your changes to the database (when "AutoCommit" is off):
データベースへの変更をコミットするためには("AutoCommit" がオフの時):
$dbh->commit; # or call $dbh->rollback; to undo changes
Finally, when you have finished working with the data source, you should "disconnect" from it:
最後に、データソースでの作業を終了するときにはそこから 切断("disconnect" )しなければいけません:
$dbh->disconnect;
一般的なインターフェース規則と留意事項¶
The DBI does not have a concept of a "current session". Every session has a handle object (i.e., a $dbh) returned from the connect method. That handle object is used to invoke database related methods.
DBI には「現在のセッション」という考えはありません。 各セッションは connectメソッドから返されるハンドルオブジェクト (つまり $dbh)を持ちます。 そのハンドルオブジェクトがデータベース関連のメソッドを呼び出すために 使われます。
Most data is returned to the Perl script as strings. (Null values are returned as undef.) 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.
ほとんどのデータは文字列として Perl スクリプトに返されます(Null 値は undef として返されます)。 これにより任意の桁数の数値データを精度を落とすことなく扱うことができます。 文字列を数値として扱う際に、Perl が同じ精度を保たないかも しれないということに注意してください。
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.
日付(Date)、時刻(Time)は、対応するデータベースエンジンの現在の デフォルトフォーマットの文字列として返されます。 時間帯の影響はデータベース/ドライバに存します。
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.
Perl スクリプトは文字列のなかにあるバイナリデータをサポートします。 DBI はバイナリデータを変更することなく、ドライバとやりとりします。 そのようなバイナリデータをどのように扱いたいのかを決めることはドライバの 実装者次第です。
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.
Perl は 2 種類の文字列に対応しています: Unicode (内部では utf8) と 非-Unicode (もしエンコーディングを仮定することを強制されるなら デフォルトは iso-8859-1)。 ドライバはどちらの種類の文字列も受け付けて、もし必要ならデータベースが 使っている文字集合に変換できるべきです。 同様に、iso-8859-1 でない データベース文字データをフェッチしたときには、 ドライバは utf8 に変換するべきです。
Multiple SQL statements may not be combined in a single statement handle ($sth), although some databases and drivers do support this (notably Sybase and SQL Server).
データベース、ドライバによってはそれをサポートしているとしても (特に Sybaseと SQL Server)、複数の SQL 文は1つの 文ハンドル($sth)に結び付けられないかもしれません。
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.
このバージョンの DBI では順序通りでないレコードの読み込みはできません。 いいかえればレコードは、データベースが返してきた順序にしか 取り出すことはできませんし、一度取り出されると忘れ去られてしまいます。
Positioned updates and deletes are not directly supported by the DBI. See the description of the CursorName attribute for an alternative.
位置づけての更新、削除を DBI は直接サポートしていません。 その代わりとして CursorName 属性の説明をご覧ください。
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 func() method. Private driver attributes are accessed just like standard attributes.
各ドライバを実装する開発者は、使いやすいと思えば、プライベートな関数や 属性を自由に提供することができます。 プライベートなドライバ関数は DBI の func() メソッドを使って 呼び出すことができます。 プライベートなドライバ属性は標準の属性とまったく同じように アクセスすることができます。
Many methods have an optional \%attr parameter which can be used to pass information to the driver implementing the method. Except where specifically documented, the \%attr parameter can only be used to pass driver specific hints. In general, you can ignore \%attr parameters or pass it as undef.
多くのメソッドはオプションとして \%attr パラメータを受け取ります。 これを使ってドライバが実装しているメソッドに情報を渡すことができます。 特に記述されていなければ、\%attr パラメータは特定のヒントを渡す場合にのみ 使用されます。 普通は \%attr パラメータを無視するか undef を渡すことができます。
命名規則と名前空間¶
The DBI package and all packages below it (DBI::*) are reserved for use by the DBI. Extensions and related modules use the DBIx:: namespace (see http://www.perl.com/CPAN/modules/by-module/DBIx/). Package names beginning with DBD:: are reserved for use by DBI database drivers. All environment variables used by the DBI or by individual DBDs begin with "DBI_" or "DBD_".
DBI パッケージとその下のパッケージ(DBI::*) は、DBI によって 予約されてます。 エクステンションと関連するモジュールは DBIx:: 名前空間 (http://www.perl.com/CPAN/modules/by-module/DBIx/をご覧下さい)を使います。 DBD:: で始まるパッケージ名は DBI データベースドライバによって 使うように予約されています。 DBI または各 DBD によって使われるすべての環境変数は "DBI_" または "DBD_" で始まります。
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.
属性の名前に使われる文字の大文字/小文字の区別は、DBI スクリプトの 移植性において重要で大きな役割を果たしています。 属性の名前が大文字か小文字かによって、名前と値を誰が決めたのかを示すのに 使われています。
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)
名前の大文字/小文字 説明
---------------------- -------------------------------------------
大文字のみ(UPPER_CASE) 標準、つまり X/Open, SQL92 など(移植性あり)
混合(MixedCase) DBI API(移植性性あり)アンダースコア(_)は使わない
小文字のみ(lower_case) ドライバもしくはエンジンに特有(移植性なし)
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., "ora_" for Oracle, "ing_" for Ingres, etc).
最も重要なのはドライバ開発者はプライベートな属性を定義するとき、小文字の 属性しか使ってはいけないといことです。 プライベートな属性の名前は、ドライバ名もしくは適切な略語から始まらなければ なりません。 (例えば ora_ はOracle, ing_ は Ingres など).
SQL - 問い合わせ言語¶
Most DBI drivers require applications to use a dialect of SQL (Structured Query Language) to interact with the database engine. The "Standards Reference Information" section provides links to useful information about SQL.
大半の DBI ドライバではデータベースエンジンとのやりとりに、それぞれの SQL(Structured Query Language) を使うことが要求とします。 "Standards Reference Information" 章は SQL に関する有用な情報への リンクを提供しています。
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 "prepare" or "do" methods.
DBI 自身は特定の言語を使うことを必須とも必要ともしていません;言語から 独立しています。 ODBC の用語でいうとDBI は「パススルー」モード(='pass-thru' mode)に あたります。 各ドライバはそうでないかもしれません。 唯一必要なことは、"prepare" または "do" メソッドへの最初の引数として 渡される問い合せまたはその他の文は、文字による一つの文字列として 表現されなければならないことです。
For an interesting diversion on the real history of RDBMS and SQL, from the people who made it happen, see:
RDBMS と SQL の 本当の 歴史についての興味深いこぼれ話が、実際にそれを やった人達から出されています:
http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
Follow the "Full Contents" then "Intergalactic dataspeak" links for the SQL history.
SQLの歴史については "Full Contents" から "Intergalactic dataspeak" リンクを追ってみてください。
プレースホルダとバインド値¶
Some drivers support placeholders and bind values. Placeholders, 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:
ある種のドライバはプレースホルダとバインド値をサポートしています。 プレースホルダはパラメータ・マーカーとも呼ばれ、データベース文の 中の値が後で、準備(prepare)された文が実行される前に 与えられることを示すために使われます。 例えば、以下のようにして、SALES テーブルに行を挿入することができます:
INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
or the following, to select the description for a product:
あるいは PRODUCTS テーブルから製品の説明 (description) を取得できます
SELECT description FROM products WHERE product_code = ?
The ? characters are the placeholders. The association of actual values with placeholders is known as binding, and the values are referred to as bind values. Note that the ? is not enclosed in quotation marks, even when the placeholder represents a string.
? という文字がプレースホルダです。 実際の値とプレースホルダとの結びつけが バインド(binding)で、値は バインド値(bind values) として呼ばれます。 プレースホルダが文字列を表わしているとしても、? が クォーテーションマークで囲まれていないことに注意してください。
Some drivers also allow placeholders like :name and :N (e.g., :1, :2, and so on) in addition to ?, but their use is not portable.
ドライバによっては、? だけでなく、:名前 や :番号 (例えば :1, :2 など)といった形式のプレースホルダを 許しているものもありますが、それは移植可能ではありません。
If the :N form of placeholder is supported by the driver you're using, then you should be able to use either "bind_param" or "execute" to bind values. Check your driver documentation.
使っているドライバが :N 形式のプレースフォルダに対応しているなら、 値をバインドするのに "bind_param" あるいは "execute" を使えるべきです。 ドライバの文書をチェックしてみて下さい。
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:
データベースサーバでの文の評価ができず、そのため問い合わせ 計画を作成できなくなるために、多くのドライバではプレースホルダをすべての 文の要素として使えるということではありません。 例えば:
"SELECT name, age FROM ?" # wrong (will probably fail)
"SELECT name, ? FROM people" # wrong (but may not 'fail')
Also, placeholders can only represent single scalar values. For example, the following statement won't work as expected for more than one value:
またプレースホルダは一つのスカラ値だけを表わします。 例えば以下の文は複数の値を期待してもうまくいかいないでしょう:
"SELECT name, age FROM people WHERE name IN (?)" # wrong
"SELECT name, age FROM people WHERE name IN (?,?)" # two names
When using placeholders with the SQL LIKE qualifier, you must remember that the placeholder substitutes for the whole string. So you should use "... LIKE ? ..." and include any wildcard characters in the value that you bind to the placeholder.
プレースホルダを SQL の LIKE 修飾子と使う場合には、プレースホルダは 文字列全体を置き換えることを忘れてはいけません。 そのため "... LIKE ? ..." を使い、プレースホルダにバインドする値に ワイルドカードとなる文字をすべて入れなければなりません。
NULL Values
NULL 値
Undefined values, or undef, 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 age with a NULL value:
未定義値 (undef) は NULL 値を示すのに使われます。 非 NULL 値と同様、NULL 値で列を挿入および更新できます。 以下は age 列を NULL 値で挿入および更新する例です:
$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");
However, care must be taken when trying to use NULL values in a WHERE clause. Consider:
しかし WHERE 句で NULL 値を使う場合には特に注意が必要です。 以下のような場合について考えてみましょう:
SELECT fullname FROM people WHERE age = ?
Binding an undef (NULL) to the placeholder will not select rows which have a NULL age! 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 "WHERE age IS NULL".
undef (NULL) をプレースホルダにバインドしても、NULLの age を持つ行は 何も 選択されません! 少なくとも SQL 標準に準拠いているデータベースエンジンではそうです。 この理由については、使用しているデータベースエンジンの SQL のマニュアル または SQL の解説書をご覧ください。 明示的に NULL を SELECT するためには "WHERE age IS NULL"とする必要が あります。
A common issue is to have a code fragment handle a value that could be either defined or undef (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:
よくある問題の一つは、実行時に defined か undef か (非 NULL か NULL か)決定される値を扱うためのコードがあるときです。 簡単なテクニックは、必要に応じて適切な分を準備して、非 NULL の場合の プレースフォルダを置き換えることです:
$sql_clause = defined $age? "age = ?" : "age IS NULL";
$sth = $dbh->prepare(qq{
SELECT fullname FROM people WHERE $sql_clause
});
$sth->execute(defined $age ? $age : ());
The following technique illustrates qualifying a WHERE clause with several columns, whose associated values (defined or undef) are in a hash %h:
以下のテクニックは、結びつける値 (defined or undef) がハッシュ %h に 入っている複数の列の WHERE 句の作成方法を示しています:
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);
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.
上述のテクニックは実行するそれぞれの呼び出しの SQL 文のために prepare を 呼び出します。 prepare() の呼び出しはコストが高いので、上述のようにアプリケーションが 文を何回も繰り返すと性能に影響を与えるかもしれません。
A better solution is a single WHERE 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 WHERE 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 ? placeholder in a statement.
よりよい解決法は、NULL と非 NULL 比較の両方に対応した単一の WHERE 句です。 この SQL 文は全ての場合に置いて 1 回だけ prepare する必要があるので、 性能が向上します。 これに対応するためのいくつかの WHERE 句の例を以下に示します。 しかしそれぞれの例には互換性、堅牢性、単純性に欠けています。 あなたが使うデータベースエンジンでどの例が対応しているかは、 どの SQL 拡張を提供しているかと、文中のどこに ? プレースホルダが 対応しているかに依存します。
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)
Statements formed with the above WHERE clauses require execute statements as follows. The arguments are required, whether their values are defined or undef.
上述の WHERE 句の形式の文は、以下のように文を実行する必要があります。 値が defined か undef かを示す引数が必要です。
0,1,2,3) $sth->execute($age);
4,5) $sth->execute($age, $age);
6) $sth->execute($age, defined($age) ? 0 : 1);
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 OR expression.
例 0 は(前述したように)動作しないかもしれませんが、それでも(Sybase のような) いくつかのデータベースエンジンでは動作します。 例 0 は例 4, 5, 6 の一部なので、例 0 が動作すれば、例えエンジンが OR 式の 右側を正しく対応していないとしても、他の例も動作します。
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.
例 1 と 2 は頑強ではありません: これらは、どの行にも存在しない、 有効な列の値 xx (例えば '~') を提供することを求められます。 これにより、どのデータがその列に保管できないのかについて注意を 払わなければならず、クライアントがそれに従うことを 想定しなければなりません。
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.
例 5 は、関数のように動作するストアドプロシージャ (例えば SP_ISNULL) を 提供する必要があります: これは値が null かどうかをチェックして、そうなら 1 を、さもなければ 0 を返します。
Example 6, the least simple, is probably the most portable, i.e., it should work with with most, if not all, database engines.
例 6 は一番複雑ですが、おそらく一番移植性があります; つまり、 (全てでないとしても)ほとんどのデータベースエンジンで動作するはずです。
Here is a table that indicates which examples above are known to work on various database engines:
以下は様々なデータベースエンジンに対してどの例が動作すると分かっているかの 表です:
-----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
* Works only because Example 0 works.
* 例 0 が動作する場合にのみ動作します。
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 ex/ subdirectory of the DBI source distribution, or here: http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl Please use the script to help us fill-in and maintain this table.
DBI は、上述の例をあなたのデータベースでテストして動作するかどうかを 知らせてくれるサンプル perl スクリプトを提供しています。 これは DBI ソース配布の ex/ サブディレクトリか、以下の場所にあります: http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl スクリプトを、この表を埋めて保守する助けに使ってください。
Performance
性能
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 execute 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:
プレースホルダを使わなければ、上記の INSERT 文は挿入する値をリテラルで 入れなければなりませんし、各行毎に再準備(re-prepare)し、 再実行(re-execute)しなければいけません。 プレースホルダを使うと、INSERT 文を準備(prepare)する必要があるのは 1 回だけです。 各行のバインド値は execute メソッドを呼び出すときに与えることができます。 各行毎に再準備(re-prepare)する必要がなくなるので、アプリーケーションは 通常、何倍も速くなります。 以下に例を示します:
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;
See "execute" and "bind_param" for more details.
詳細は "execute" および "bind_param" をご覧ください。
The q{...} style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote like qq{...} operator if you want to interpolate variables into the string. See "Quote and Quote-like Operators" in perlop for more details.
この例では、SQL 文のなかで使われるかもしれないクォートの対応が崩れないよう、 q{...} スタイルのクォートを使っています。 文字列に解釈して欲しい変数がある場合には、qq{...} のような ダブルクォートを使うことができます。 詳細については "Quote and Quote-like Operators" in perlop をご覧ください。
See also the "bind_columns" method, which is used to associate Perl variables with the output columns of a SELECT statement.
Perl の変数を SELECT 文の出力カラムに結びつけるために使われる "bind_column" メソッドもご覧ください。
DBI パッケージとクラス¶
In this section, we cover the DBI class methods, utility functions, and the dynamic attributes associated with generic DBI handles.
このセクションでは、DBI クラスメソッド、ユーティリティ関数そして 一般的な DBI ハンドルに関連する動的属性についてカバーします。
DBI 定数¶
Constants representing the values of the SQL standard types can be imported individually by name, or all together by importing the special :sql_types tag.
以下の SQL 標準型定数は個別にインポートしたり、特殊な :sql_types タグで すべてをインポートすることができます:
The names and values of all the defined SQL standard types can be produced like this:
定義されている全ての SQL 標準型の名前と値は以下のようにして取得できます:
foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) {
printf "%s=%d\n", $_, &{"DBI::$_"};
}
These constants are defined by SQL/CLI, ODBC or both. SQL_BIGINT is (currently) omitted, because SQL/CLI and ODBC provide conflicting codes.
これらの定数は SQL/CLI, ODBC あるいは両方で定義されています。 SQL/CLI と ODBC でコードが衝突しているので、SQL_BIGINT is (現状では) 省略されています。
See the "type_info", "type_info_all", and "bind_param" methods for possible uses.
可能な利用法に関しては "type_info", "type_info_all", "bind_param" メソッドを参照してください。
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.
あるデータ型について DBI が名前付き定数を定義していないからと言って、 ドライバがそのデータ型に対応していないというわけではないことに 注意してください。
DBI クラスメソッド¶
The following methods are provided by the DBI class:
DBI クラスによって以下のメソッドが提供されています:
parse_dsn¶
($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn)
or die "Can't parse DBI DSN '$dsn'";
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.
DBI データソース名(Data Source Name) (DSN) を分解して、それぞれの部分を 返します。 $dsn に有効な DSN が含まれていない場合、parse_dsn() は空リストを返します。
$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:
$scheme は DSN の最初の部分で、現在のところ常に 'dbi' です。 $driver はドライバ名で、おそらくデフォルトは $ENV{DBI_DRIVER} で、 未定義値かもしれません。 $attr_string はオプションの属性文字列の内容で、未定義値かもしれません。 $attr_string が空でないなら、$attr_hash はパースされた属性名と値を含む ハッシュへのリファレンスです。 $driver_dsn は DBI DSN 文字列の最後の部分です。 例えば:
($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';
The parse_dsn() method was added in DBI 1.43.
parse_dsn() メソッドは DBI 1.43 で追加されました。
connect¶
$dbh = DBI->connect($data_source, $username, $password)
or die $DBI::errstr;
$dbh = DBI->connect($data_source, $username, $password, \%attr)
or die $DBI::errstr;
Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds. Use $dbh->disconnect to terminate the connection.
要求された $data_source への接続またはセッションを確立します。 接続が成功するとデータベース・ハンドル・オブジェクトを返します。 接続を終わらせるためには $dbh->disconnect を使います。
If the connect fails (see below), it returns undef and sets both $DBI::err and $DBI::errstr. (It does not explicitly set $!.) You should generally test the return status of connect and print $DBI::errstr if it has failed.
connect が失敗したら(下記をご覧下さい)undefを返し、 $DBI::err, $DBI::errstr を設定します ($! は明示的には 設定しません)。 一般的には connect の戻りステータスを確認し、失敗していたら $DBI::errstr を表示します。
Multiple simultaneous connections to multiple databases through multiple drivers can be made via the DBI. Simply make one connect call for each database and keep a copy of each returned database handle.
DBI 経由で、複数のデータベースに対しての複数のドライバを使って、同時に 複数接続することができます。 単純に各データベース毎に connect を呼び出し、返された データベースハンドルのコピーをとっておいてください。
The $data_source value must begin with "dbi:driver_name:". The driver_name specifies the driver that will be used to make the connection. (Letter case is significant.)
$data_source の値は "dbi:ドライバ名:" で 始まらなければなりません。 ドライバ名 が接続ために使われるドライバを示します。 (大文字小文字は区別されます).
As a convenience, if the $data_source parameter is undefined or empty, the DBI will substitute the value of the environment variable DBI_DSN. If just the driver_name part is empty (i.e., the $data_source prefix is "dbi::"), the environment variable DBI_DRIVER is used. If neither variable is set, then connect dies.
便宜上、$data_source フィールドが未定義あるいは空だった場合、DBI は この値を環境変数 DBI_DSN の値で置換します。 ドライバ名の部分だけが空だった場合(つまり $data_source の始まりが "dbi::") 、環境変数 DBI_DRIVER が使われます。 もし変数も設定されていなければ connect は die します。
Examples of $data_source values are:
$data_source の値の例は:
dbi:DriverName:database_name
dbi:DriverName:database_name@hostname:port
dbi:DriverName:database=database_name;host=hostname;port=port
There is no standard 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.
ドライバ名の後ろにつく文字列については 標準はありません。 各ドライバは欲しい書き方をどんなものでも自由に使うことができます。 DBI が要求するのは、すべての情報が一つの文字列として与えられることだけです。 使っているドライバが要求している書き方の説明の説明については、その ドキュメントを調べなければなりません。
It is recommended that drivers support the ODBC style, shown in the last example above. It is also recommended that that they support the three common names 'host', 'port', and 'database' (plus 'db' as an alias for database). This simplifies automatic construction of basic DSNs: "dbi:$driver:database=$db;host=$host;port=$port". 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.
ドライバは上述の最後の例である ODBC 形式に対応することが推奨されています。 また、三つの共通の名前 'host', 'port', 'database' (および database の別名としての 'db') に対応することも推奨されています。 これにより基本的な DSN の自動的な構築が簡単になります: "dbi:$driver:database=$db;host=$host;port=$port"。 ドライバは、DSN がこの形式で与えられたとき、「何か意味のあることをする」 ことを目指すべきですが、(Infomix にとっての 'port' のように)どれかの部分が このドライバにとって意味がない場合、その部分が空でないときには エラーを発生させるべきです。
If the environment variable DBI_AUTOPROXY is defined (and the driver in $data_source is not "Proxy") then the connect request will automatically be changed to:
環境変数 DBI_AUTOPROXY が定義されていれば(そして $data_source の データソースが "Proxy" でなければ)、接続要求は自動的に以下のように 変更されます:
$ENV{DBI_AUTOPROXY};dsn=$data_source
DBI_AUTOPROXY is typically set as "dbi:Proxy:hostname=...;port=...". If $ENV{DBI_AUTOPROXY} doesn't begin with 'dbi:' then "dbi:Proxy:" will be prepended to it first. See the DBD::Proxy documentation for more details.
DBI_AUTOPROXY は、通常 "dbi:Proxy:hostname=...;port=..." となります。 $ENV{DBI_AUTOPROXY} が 'dbi:' で始まっていない場合は、先頭に "dbi:Proxy:" を追加します。 詳細については DBD::Proxyドキュメント をご覧ください。
If $username or $password are undefined (rather than just empty), then the DBI will substitute the values of the DBI_USER and DBI_PASS 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.
$username または $password が未定義(あるいは単に空)ならば、 DBI はそれぞれ環境変数 DBI_USER と DBI_PASS の値で置き換えます。 その環境変数が定義されてなければ、DBI は警告します。 しかしながら、これらの環境変数を普段使いすることは、セキュリティ上の理由から お勧めしません。 この機能は基本的にテストを簡単にすることを目的としています。 ユーザー名とパスワードを指定するための代替案については後述します。
DBI->connect automatically installs the driver if it has not been installed yet. Driver installation either returns a valid driver handle, or it dies with an error message that includes the string "install_driver" and the underlying problem. So DBI->connect will die on a driver installation failure and will only return undef on a connect failure, in which case $DBI::errstr will hold the error message. Use eval { ... } if you need to catch the "install_driver" error.
DBI->connect は、まだインストールされていないドライバを自動的に インストールします。 ドライバのインストールは適切なドライバハンドルを返すか、 "install_driver" という文字列と基になった問題が入った エラーメッセージとともに die するかのどちらかです。 そのため DBI->connect はドライバインストールの障害のときには die して、接続の障害のときには undef を返すだけです; そのときには $DBI::errstr にエラーの情報が入っています。 "install_driver" エラーを捕捉する必要がある場合は eval { ... } を 使ってください。
The $data_source argument (with the "dbi:...:" prefix removed) and the $username and $password 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 $data_source, $username, and $password 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 $data_source is specified.)
$data_source 引数 ( "dbi:...:" という接頭辞をとったもの)と $username, $password の引数は、処理のためドライバに渡されます。 DBI はこれらのフィールドの内容の解釈について何も定義していません。 ドライバは $data_source, $username, $password のフィールドを、 どんなふうにも自由に解析することができます。 そしてアクセスされるエンジンに合わせて、いかなるデフォルトも 設定することができます。 (例えば Oracle では、データソースが指定されていなければ、環境変数 ORACLE_SID と TWO_TASK を使います)。
The AutoCommit and PrintError attributes for each connection default to "on". (See "AutoCommit" and "PrintError" for more information.) However, it is strongly recommended that you explicitly define AutoCommit rather than rely on the default. The PrintWarn attribute defaults to on if $^W is true, i.e., perl is running with warnings enabled.
各コネクションの AutoCommit と PrintError 属性のデフォルトは "on" です。 (詳細は AutoCommit と PrintError をご覧ください)。 しかしながら、デフォルトにまかませるよりも明示的に AutoCommit を 定義することが強く推奨されます。 $^W が真なら PrintWarn 属性のデフォルトはオンです; つまり、perl は 警告を有効にして動作します。
The \%attr parameter can be used to alter the default settings of PrintError, RaiseError, AutoCommit, and other attributes. For example:
\%attr パラメータを使って、PrintError, RaiseError, AutoCommit などの属性のデフォルト値を変更することができます。 例:
$dbh = DBI->connect($data_source, $user, $pass, {
PrintError => 0,
AutoCommit => 0
});
The username and password can also be specified using the attributes Username and Password, in which case they take precedence over the $username and $password parameters.
ユーザー名とパスワードは属性 Username と Password を使っても 指定でき、この場合は $username と $password のパラメータより 優先されます。
You can also define connection attribute values within the $data_source parameter. For example:
$data_source パラメータの中で接続属性の値を定義することもできます。 例:
dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...
Individual attributes values specified in this way take precedence over any conflicting values specified via the \%attr parameter to connect.
この方法で指定される各属性値は、connect への \%attr パラメータを 介して指定された値とぶつかっても優先されます。
The dbi_connect_method 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).
dbi_connect_method 属性は接続を確立するさいにどちらのドライバメソッドが 呼ばれるべきかを指定するために使われます。 これには 'connect', 'connect_cached', 'Apache::DBI::connect' これは Apache で実行されたときには自動的にデフォルトになります)のような ある特別なケースが使えます。
Where possible, each session ($dbh) 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.
可能であれば、各セッション ($dbh) は他のセッションのトランザクションから 独立しています。 これはカーソルをトランザクションをまたがってオープンしたままにする必要がある 場合には便利です。 例えばあるセッションを長い寿命をもつカーソル(通常は読み込み専用)のために使い、 他のセッションで短い更新トランザクションを実行する場合です。
For compatibility with old DBI scripts, the driver can be specified by passing its name as the fourth argument to connect (instead of \%attr):
古い DBI スクリプトとの互換性のために、ドライバの名前を connect の 4 番目の引数として(\%attr の代わりに)、ドライバに指定することができます:
$dbh = DBI->connect($data_source, $user, $pass, $driver);
In this "old-style" form of connect, the $data_source should not start with "dbi:driver_name:". (If it does, the embedded driver_name will be ignored). Also note that in this older form of connect, the $dbh->{AutoCommit} attribute is undefined, the $dbh->{PrintError} attribute is off, and the old DBI_DBNAME environment variable is checked if DBI_DSN is not defined. Beware that this "old-style" connect will soon be withdrawn in a future version of DBI.
この connect の「旧スタイル」形式では、$data_source は "dbi:ドライバ名:" で始まってはいけません。 (もしそうであれば、埋め込まれたドライバ名は無視されます)。 この古い形式の connectでは、$dbh->{AutoCommit} 属性は未定義、 $dbh->{PrintError} はオフ、そして DBI_DSN が定義されていなければ、 古い DBI_DBNAME 環境変数がチェックされます。 この「旧スタイル」の connect は DBI の近い将来のバージョンで 撤廃されるであろうということに用心してください。
connect_cached¶
$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;
connect_cached is like "connect", except that the database handle returned is also stored in a hash associated with the given parameters. If another call is made to connect_cached with the same parameter values, then the corresponding cached $dbh 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 ping method fails.
connect_cached は返されるデータベースハンドルが与えられたパラメータと 関連付けられてハッシュにも格納されるという点を除けば、"connect" に 似ています。 同じパラメータ値で connect_cached がもう一度呼ばれると、それがまだ 適切であれば、キャッシュされた対応する $dbh が返されます。 すでに切断されていたり、ping メソッドが失敗したら、キャッシュされた データベースハンドルは新しい接続で置きかえられます。
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 connect_cached will use it.
このメソッドの動きは、Apache::DBI によって実装されている永続接続の動きとは 多くの点で異なることに注意してください。 しかし、Apache::DBI が読み込まれると、connect_cached はこれを 使います。
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 AutoCommit attribute.
キャッシュは、あるアプリケーションによっては便利かもしれませんが、 たくさん接続しすぎるといった問題もおこすかもしれませんし、注意して 使わなければなりません。 とくに、connect_cached() で作成したデータベースハンドルの属性を 変えることは避けてください; 同じハンドルを使っている他のコードに 影響を与えることになるからです。 connect_cached() がハンドルを返すとき、属性は初期値にリセットされます。 これは(特に AutoCommit 属性で) 問題になる可能性があります。
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:
プログラムの複数の部分がconnect_cached()を使用して、同じ(初期)属性で同じデータベースに接続している場合は、connect_cached()コールにプライベート属性を追加して、キャッシュの範囲を効果的に制限することをお薦めします。 次に例を示します。 (TBR)
DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... });
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 private_foo_cachekey here as an example, you can use any attribute name with a private_ prefix.)
そのconnect_cached()呼び出しから返されたハンドルは、コード内の他のconnect_cached()呼び出しによっても同じ属性値(プライベート値を含む)が渡される場合にのみ、その他のconnect_cached()呼び出しによって返されます(ここでは例としてprivate_foo_cachekeyを使用しています。 private_プレフィクスを持つ任意の属性名を使用できます)。 (TBR)
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:
これをさらに一歩進めて、private属性をその場所に固有の値に設定することで、特定のconnect_cached()呼び出しがコード内のその場所に固有のハンドルを返すように制限できます。 (TBR)
DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... });
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.
private属性を使用しても、connect_cached()の個々の呼び出しの接続キャッシュを取得できますが、コードの別々の部分に対して別々のデータベース接続を作成することにより、データベースハンドルは、他のハンドルに対して行われた属性の変更から分離されます。 (TBR)
The cache can be accessed (and cleared) via the "CachedKids" attribute:
キャッシュは "CachedKids" 属性を介してアクセス(そしてクリア)することが できます:
my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
%$CachedKids_hashref = () if $CachedKids_hashref;
available_drivers¶
@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);
Returns a list of all available drivers by searching for DBD::* modules through the directories in @INC. 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 $quiet will inhibit the warning.
@INC のディレクトリから DBD::* モジュールを検索して、使用可能な ドライバのリストを返します。 デフォルトでは、先に見つかったディレクトリにある同じ名前のものにより、 隠されてしまうドライバがあれば警告します。 警告を抑止するには $quiet を真の値にします。
installed_drivers¶
%drivers = DBI->installed_drivers();
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.
現在のプロセスに「インストールされた」(読み込まれた)全てのドライバの ドライバ名とドライバハンドルの組のリストを返します。 ドライバ名には 'DBD::' 接頭辞は付いていません。
To get a list of all drivers available in your perl installation you can use "available_drivers".
インストールされている perl で利用可能な全てのドライバのリストを得るには、 "available_drivers" が使えます。
Added in DBI 1.49.
DBI 1.49 で追加されました。
installed_versions¶
DBI->installed_versions;
@ary = DBI->installed_versions;
%hash = DBI->installed_versions;
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 DBI::PurePerl drivers which appear not be pure-perl are ignored.
available_drivers() を呼び出して、そのそれぞれに対して install_driver() を 使って読み込もうとします。 読み込みに成功したドライバの名前とバージョン番号はハッシュに追加されます。 DBI::PurePerl ドライバで実行するとピュア perl でないように見える ドライバは無視されます。
When called in array context the list of successfully loaded drivers is returned (without the 'DBD::' prefix).
配列コンテキストで呼び出されると、読み込みに成功したドライバのリストが ('DBD::' の接頭辞なしで) 返されます。
When called in scalar context a reference to the hash is returned and the hash will also contain other entries for the DBI version, OS name, etc.
スカラコンテキストで呼び出されると、ハッシュへのリファレンスが返され、 このハッシュには DBI バージョン、OS 名などのその他のエントリも 含まれます。
When called in a void context the installed_versions() method will print out a formatted list of the hash contents, one per line.
無効コンテキストで呼び出されると、installed_versions() メソッドは ハッシュの内容を行単位でフォーマットしたリストを出力します。
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.
潜在的にメモリコストが高いことと、何個か分からないシステムに インストールされているドライバを読み込むという不明なリスクがあるので、 このメソッドは一般的な使用は推奨されません。 代わりに available_drivers() を使ってください。
The installed_versions() method is primarily intended as a quick way to see from the command line what's installed. For example:
installed_versions() メソッドは主としてインストールされているものを コマンドラインから素早く見ることを目的としています。 例えば:
perl -MDBI -e 'DBI->installed_versions'
The installed_versions() method was added in DBI 1.38.
installed_versions() メソッドは DBI 1.38 で追加されました。
data_sources¶
@ary = DBI->data_sources($driver);
@ary = DBI->data_sources($driver, \%attr);
Returns a list of data sources (databases) available via the named driver. If $driver is empty or undef, then the value of the DBI_DRIVER environment variable is used.
指定された名前のドライバで使うことができるデータソース(データベース)の リストを返します。 $driver が空もしくは undef であれば、環境変数 DBI_DRIVER の値が 使われます。
The driver will be loaded if it hasn't been already. Note that if the driver loading fails then data_sources() dies with an error message that includes the string "install_driver" and the underlying problem.
まだロードされていなければ、ドライバはロードされます。 もしドライバのローディングが失敗したら、"install_driver" という文字列と そこにある問題が入ったエラーメッセージで die することに注意してください。
Data sources are returned in a form suitable for passing to the "connect" method (that is, they will include the "dbi:$driver:" prefix).
データソースは "connect" メソッドに渡すのに適したな形式で返されます (つまり接頭辞 "dbi:$driver:" が入ります。)
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.
多くのドライバが利用できるデータソースを調べる方法を 持っていないということに注意してください。 これらのドライバは空もしくは不完全なリストが返したり、 あるいはドライバ特有の属性が与えられることを必要とするかもしれません。
There is also a data_sources() method defined for database handles.
データベースハンドルのために定義されている data_sources() メソッドも あります。
trace¶
DBI->trace($trace_setting)
DBI->trace($trace_setting, $trace_filename)
DBI->trace($trace_setting, $trace_filehandle)
$trace_setting = DBI->trace;
The DBI->trace method sets the global default trace settings and returns the previous trace settings. It can also be used to change where the trace output is sent.
DBI->trace メソッドは グローバルにデフォルトの トレース設定を セットし、以前の トレース設定を返します。 これはまた、トレース出力をどこに送るかを変更するためにも使います。
There's a similar method, $h->trace, which sets the trace settings for the specific handle it's called on.
似たようなメソッドして $h->trace があり、これは呼び出された 特定のハンドルのトレース設定を設定します。
See the "TRACING" section for full details about the DBI's powerful tracing facilities.
DBI の強力なトレース機能に関する完全な詳細については "TRACING" の章を参照してください。
visit_handles¶
DBI->visit_handles( $coderef );
DBI->visit_handles( $coderef, $info );
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.
$coderef はサブルーチンへのリファレンスで、$info は任意の値であり、 もし未定義ならデフォルトはからハッシュへのリファレンスとなります。 $info を返します。
For each installed driver handle, if any, $coderef is invoked as:
インストールされているドライバがあれば、そのハンドル毎に、 $coderef は以下のようにして起動されます:
$coderef->($driver_handle, $info);
If the execution of $coderef returns a true value then "visit_child_handles" is called on that child handle and passed the returned value as $info.
$coderef の実行によって真の値が返されると、"visit_child_handles" が 子ハンドルに呼び出され、返された値を $info として渡します。
For example:
例えば:
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
});
See also "visit_child_handles".
"visit_child_handles" も参照してください。
DBI ユーティリティ関数¶
In addition to the DBI methods listed in the previous section, the DBI package also provides several utility functions.
前のセクションで一覧ししたメソッドに加えて、DBIパッケージはいくつかの ユーティリティ関数も提供しています。
These can be imported into your code by listing them in the use statement. For example:
これらは use 文でリストすることであなたのコードにインポートできます。 例えば:
use DBI qw(neat data_diff);
Alternatively, all these utility functions (except hash) can be imported using the :utils import tag. For example:
あるいは、(hash を除く)これらのユーティリティ関す全てを :utils インポートタグを使ってインポートできます。 例えば:
use DBI qw(:utils);
data_string_desc¶
$description = data_string_desc($string);
Returns an informal description of the string. For example:
文字列に関する略式の記述を返します。 例えば:
UTF8 off, ASCII, 42 characters 42 bytes
UTF8 off, non-ASCII, 42 characters 42 bytes
UTF8 on, non-ASCII, 4 characters 6 bytes
UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes
UTF8 off, undef
The initial UTF8 on/off refers to Perl's internal SvUTF8 flag. If $string has the SvUTF8 flag set but the sequence of bytes it contains are not a valid UTF-8 encoding then data_string_desc() will report UTF8 on but INVALID encoding.
最初の UTF8 on/off は Perl 内部の SvUTF8 フラグを参照します。 $string に SvUTF8 フラグがセットされているけれどもその内容が有効な UTF-8 エンコーディングでない場合、data_string_desc() は UTF8 on but INVALID encoding と報告します。
The ASCII vs non-ASCII portion shows ASCII if all the characters in the string are ASCII (have code points <= 127).
ASCII と non-ASCII の部分は、文字列の 全ての 文字が ASCII (文字位置が <= 127) なら ASCII となります。
The data_string_desc() function was added in DBI 1.46.
data_string_desc() 関数は DBI 1.46 で追加されました。
data_string_diff¶
$diff = data_string_diff($a, $b);
Returns an informal description of the first character difference between the strings. If both $a and $b contain the same sequence of characters then data_string_diff() returns an empty string. For example:
二つの文字列の間で最初に異なる文字の非公式な説明を返します。 $a と $b が同じ文字並びなら、data_string_diff() は空文字列を返します。 例えば:
Params a & b Result
------------ ------
'aaa', 'aaa' ''
'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b'
'aaa', undef 'String b is undef, string a has 3 characters'
'aaa', 'aa' 'String b truncated after 2 characters'
Unicode characters are reported in \x{XXXX} format. Unicode code points in the range U+0800 to U+08FF are unassigned and most likely to occur due to double-encoding. Characters in this range are reported as \x{08XX}='C' where C is the corresponding latin-1 character.
Unicode 文字は \x{XXXX} 形式で報告されます。 U+0800 から U+08FF の範囲の Unicode 符号位置は未定義で、もっとも ありそうなことは二重エンコーディングです。 この範囲の文字は \x{08XX}='C' として報告されます; ここで C は対応する latin-1 文字です。
The data_string_diff() function only considers logical characters and not the underlying encoding. See "data_diff" for an alternative.
data_string_diff() 関数は、論理的な 文字 だけを考慮し、その 基礎となるエンコーディングは考慮しません。 代替案に関しては "data_diff" を参照してください。
The data_string_diff() function was added in DBI 1.46.
data_string_diff() 関数は DBI 1.46 で追加されました。
data_diff¶
$diff = data_diff($a, $b);
$diff = data_diff($a, $b, $logical);
Returns an informal description of the difference between two strings. It calls "data_string_desc" and "data_string_diff" and returns the combined results as a multi-line string.
二つの文字列の違いに関する非公式な説明を返します。 これは "data_string_desc" と "data_string_diff" を呼び出し、 結合した結果を複数行の文字列として返します。
For example, data_diff("abc", "ab\x{263a}") will return:
例えば、data_diff("abc", "ab\x{263a}") は以下のものを返します:
a: UTF8 off, ASCII, 3 characters 3 bytes
b: UTF8 on, non-ASCII, 3 characters 5 bytes
Strings differ at index 2: a[2]=c, b[2]=\x{263A}
If $a and $b are identical in both the characters they contain and their physical encoding then data_diff() returns an empty string. If $logical is true then physical encoding differences are ignored (but are still reported if there is a difference in the characters).
$a と $b が、含まれている文字列 および その物理的なエンコーディングの 両方において同一の場合、data_diff() は空文字列を返します。 $logical が新なら物理的なエンコーディングの違いは無視されます (しかし文字に違いがあればやはり報告されます)。
The data_diff() function was added in DBI 1.46.
data_diff() 関数は DBI 1.46 で追加されました。
neat¶
$str = neat($value);
$str = neat($value, $maxlen);
Return a string containing a neat (and tidy) representation of the supplied value.
与えられた文字列を整然と(そしてきれいに)整えられた文字列を返します。
Strings will be quoted, although internal quotes will not be escaped. Values known to be numeric will be unquoted. Undefined (NULL) values will be shown as undef (without quotes).
文字列はクォーテーションで囲まれますが、文字列の中のクォーテーションは エスケープ されません。 数値であるとわかっている値はクォーテーションで囲まれません。 未定義(NULL) 値は(クォートなしで)undef で表されます。
If the string is flagged internally as utf8 then double quotes will be used, otherwise single quotes are used and unprintable characters will be replaced by dot (.).
文字列が内部で UTF8 として記録されていると、ダブルクォートが使われ、 さもなければシングルクォートが使われ、表示できない文字は点(.)で 置き換えられます。
For result strings longer than $maxlen the result string will be truncated to $maxlen-4 and "...'" will be appended. If $maxlen is 0 or undef, it defaults to $DBI::neat_maxlen which, in turn, defaults to 400.
変換結果の文字列が $masxlen よりも長ければ、文字列は $maxlen-4 の 長さに切り詰め、"...'" が後ろにつけられます。 $maxlen が 0 または undef であれば、$DBI::neat_maxlen (デフォルトは400)が代りにデフォルトになります。
This function is designed to format values for human consumption. It is used internally by the DBI for "trace" output. It should typically not be used for formatting values for database use. (See also "quote".)
この関数は人の目にわかりやすいように値の形式を整えるように考えられています。 これは DBI 内部で "trace" 出力に使われています。 通常データベースが利用するよう、値の形を整えるために使っては いけません ("quote" もご覧ください)。
neat_list¶
$str = neat_list(\@listref, $maxlen, $field_sep);
Calls neat on each element of the list and returns a string containing the results joined with $field_sep. $field_sep defaults to ", ".
リストの各要素に neat を呼び出し、その結果を $field_sep でつなげた 結果の文字列を返します。 $field_sep のデフォルトは ", " です。
looks_like_number¶
@bool = looks_like_number(@array);
Returns true for each element that looks like a number. Returns false for each element that does not look like a number. Returns undef for each element that is undefined or empty.
リストの各要素について数値に見えば真を返します。 各要素が数値に見えなければ偽を返します。 各要素が未定義あるいは空であれば、undef もしくは空を返します。
hash¶
$hash_value = DBI::hash($buffer, $type);
Return a 32-bit integer 'hash' value corresponding to the contents of $buffer. The $type parameter selects which kind of hash algorithm should be used.
$buffer の内容に対応する 32 ビット整数の「ハッシュ」値を返します。 $type パラメータは使用するハッシュアルゴリズムを選択します。
For the technically curious, type 0 (which is the default if $type isn't specified) is based on the Perl 5.1 hash except that the value is forced to be negative (for obscure historical reasons). Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See http://www.isthe.com/chongo/tech/comp/fnv/ for more information. Both types are implemented in C and are very fast.
技術的好奇心のために、型 0 (これは $type が指定されなかったときの デフォルトです) は Perl 5.1 ハッシュを基にしていますが、(はっきりしない 歴史的な理由により) 値は負数に制限されます。 型 1 はよりより "Fowler / Noll / Vo" (FNV) ハッシュです。 さらなる情報については http://www.isthe.com/chongo/tech/comp/fnv/ を 参照してください。 どちらの型も C で実装されていてとても速いです。
This function doesn't have much to do with databases, except that it can be handy to store hash values in a database.
この関数はデータベースに対して何かをするというものではありませんが、 データベースにハッシュ値を補完するのに便利です。
sql_type_cast¶
$sts = DBI->sql_type_cast($sv, $sql_type, $flags);
sql_type_cast attempts to cast $sv to the SQL type (see "DBI Constants") specified in $sql_type. At present only the SQL types SQL_INTEGER, SQL_DOUBLE and SQL_NUMERIC are supported.
sql_type_cast は $sv を $sql_type で定義されている SQL 型 ("DBI Constants" 参照) にキャストしようとします。 現在のところ SQL 型 SQL_INTEGER, SQL_DOUBLE, SQL_NUMERIC のみに 対応しています。
For SQL_INTEGER the effect is similar to using the value in an expression that requires an integer. It gives the perl scalar an 'integer aspect'. (Technically the value gains an IV, or possibly a UV or NV if the value is too large for an IV.)
SQL_INTEGERの場合、この効果は、整数を必要とする式で値を使用するのと似ています。 perlスカラーに「整数アスペクト」を与えます。 (技術的には、値はIVを取得します。 IVに対して値が大きすぎる場合は、UVまたはNVを取得する可能性があります。 ) (TBR)
For SQL_DOUBLE the effect is similar to using the value in an expression that requires a general numeric value. It gives the perl scalar a 'numeric aspect'. (Technically the value gains an NV.)
SQL_DOUBLEの場合、この効果は、一般的な数値を必要とする式で値を使用することに似ています。 perlスカラーに「数値的な側面」を与えます(技術的には、値はNVを獲得します)。 (TBR)
SQL_NUMERIC is similar to SQL_INTEGER or SQL_DOUBLE but more general and more cautious. It will look at the string first and if it looks like an integer (that will fit in an IV or UV) it will act like SQL_INTEGER, if it looks like a floating point value it will act like SQL_DOUBLE, if it looks like neither then it will do nothing - and thereby avoid the warnings that would be generated by SQL_INTEGER and SQL_DOUBLE when given non-numeric data.
SQL_NUMERICはSQL_INTEGERやSQL_DOUBLEに似ていますが、より一般的でより慎重です。 SQL_NUMERICは文字列を最初に見て、(IVまたはUVに適合する)整数のように見える場合はSQL_INTEGERのように動作し、浮動小数点値のように見える場合はSQL_DOUBLEのように動作し、どちらでもないように見える場合は何もしません。 これにより、非数値データが与えられたときにSQL_INTEGERとSQL_DOUBLEによって生成される警告を回避します。 (TBR)
$flags may be:
$flags は:
DBIstcf_DISCARD_STRING-
If this flag is specified then when the driver successfully casts the bound perl scalar to a non-string type then the string portion of the scalar will be discarded.
このフラグを指定すると、ドライバがバインドされたperlスカラーを文字列以外の型にキャストしたときに、スカラーの文字列部分が破棄されます。 (TBR)
DBIstcf_STRICT-
If
$svcannot be cast to the requested$sql_typethen by default it is left untouched and no error is generated. If you specifyDBIstcf_STRICTand the cast fails, this will generate an error.$svが要求された$sql_typeにキャストできない場合、デフォルトでは変更されず、エラーは生成されません。DBIstcf_STRICTを指定してキャストが失敗すると、エラーが生成されます。 (TBR)
The returned $sts value is:
返された $sts の値は:
-2 sql_type is not handled
-1 sv is undef so unchanged
0 sv could not be cast cleanly and DBIstcf_STRICT was used
1 sv could not be case and DBIstcf_STRICT was not used
2 sv was cast successfully
This method is exported by the :utils tag and was introduced in DBI 1.611.
このメソッドは :utils タグでエクスポートされ、DBI 1.611 で 導入されました。
DBI 動的属性¶
Dynamic attributes are always associated with the last handle used (that handle is represented by $h in the descriptions below).
動的属性は 最後に使われたハンドル に関連づけられます。 (そのハンドルは以下の説明では $h で示されます)
Where an attribute is equivalent to a method call, then refer to the method call for all related documentation.
属性がメソッド呼び出しと同様のところでは、すべての関連する ドキュメンテーションでそのメソッド呼び出しを参照してください。
Warning: these attributes are provided as a convenience but they do have limitations. Specifically, they have a short lifespan: because they are associated with the last handle used, they should only be used immediately after calling the method that "sets" them. If in any doubt, use the corresponding method call.
警告: 便宜上、これらの属性を用意していますが、限界があります。 特にこれらの有効な時間は長くありません: 最後に使われたハンドルに 関連付けられているために、それらを「設定した」メソッドを呼び出した すぐ後 にしか使うことができません。 少しでも疑問があれば、対応するメソッド呼び出しを使ってください。
$DBI::err¶
Equivalent to $h->err.
$h->err と等価です。
$DBI::errstr¶
Equivalent to $h->errstr.
$h->errstr と等価です。
$DBI::state¶
Equivalent to $h->state.
$h->state と等価です。
$DBI::rows¶
Equivalent to $h->rows. Please refer to the documentation for the "rows" method.
$h->rows と等価です。 "rows" メソッドの文書を参照してください。
$DBI::lasth¶
Returns the DBI object handle used for the most recent DBI method call. If the last DBI method call was a DESTROY then $DBI::lasth will return the handle of the parent of the destroyed handle, if there is one.
最後の DBI メソッド呼び出しに使われた DBI オブジェクトハンドルを返します。 最後の DBI メソッド呼び出しが DESTROY であれば、$DBI::lasth はもしあれば、 破壊されたハンドルの親のハンドルを返します。
全てのハンドルに共通のメソッド¶
The following methods can be used by all types of DBI handles.
以下のメソッドは DBI ハンドルのすべてのタイプに使うことができます。
err¶
$rv = $h->err;
Returns the native database engine error code from the last driver method called. The code is typically an integer but you should not assume that.
最後のドライバ関数呼び出しについて ネイティブ なデータベースエンジン エラーコードを返します。 コードは典型的には整数ですが、それを想定するべきではありません。
The DBI resets $h->err to undef before almost all DBI method calls, so the value only has a short lifespan. Also, for most drivers, the statement handles share the same error variable as the parent database handle, so calling a method on one handle may reset the error on the related handles.
DBI はほとんど全ての DBI メソッドを呼び出す前に $h->err を undef に リセットするので、この値は短い間だけ有効です。 またほとんどのドライバでは、文ハンドルは同じエラー変数を 親データベースハンドルと共有するので、あるハンドルに対してメソッドを呼び出すと、 関連するtハンドルのエラーをリセットするかもしれません。
(Methods which don't reset err before being called include err() and errstr(), obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the tied hash attribute FETCH() and STORE() methods.)
(コールされる前にerrをリセットしないメソッドには、err()とerrstr()、もちろんstate()、rows()、func()、trace()、trace_msg()、ping()、そしてタイハッシュ属性のFETCH()メソッドとSTORE()メソッドが含まれます。 (TBR)
If you need to test for specific error conditions and have your program be portable to different database engines, then you'll need to determine what the corresponding error codes are for all those engines and test for all of them.
特定のエラー状況についてテストする必要があり、かつ あなたのプログラムが 他のデータベース・エンジンに対して移植可能にする必要があれば、それら すべてのエンジンについて対応するエラーコードが何かを判定し、それらの すべてについてテストする必要があります。
The DBI uses the value of $DBI::stderr as the err value for internal errors. Drivers should also do likewise. The default value for $DBI::stderr is 2000000000.
DBI は $DBI::stderr の値を、内部エラーのための err 値として使います。 ドライバも似たようなことをします。 $DBI::stderr のデフォルト値は 2000000000 です。
A driver may return 0 from err() to indicate a warning condition after a method call. Similarly, a driver may return an empty string to indicate a 'success with information' condition. In both these cases the value is false but not undef. The errstr() and state() methods may be used to retrieve extra information in these cases.
ドライバはerr()から0を返して、メソッド呼び出し後の警告条件を示すことができます。 同様に、ドライバは'success with information'条件を示すために空の文字列を返すことができます。 これらの両方の場合、値はfalseですが、undefではありません。 errstr()およびstate()メソッドは、これらの場合に追加情報を取得するために使用できます。 (TBR)
See "set_err" for more information.
さらなる情報については "set_err" を参照してください。
errstr¶
$str = $h->errstr;
Returns the native database engine error message from the last DBI method called. This has the same lifespan issues as the "err" method described above.
最後の DBI 関数呼び出しについて、ネイティブなデータベースエンジンエラーメッセージを返します。 上記で説明した "err" メソッドと同じ有効期間の問題を持っています。
The returned string may contain multiple messages separated by newline characters.
返された文字列は改行文字で区切られた複数のメッセージを 含んでいるかもしれません。
The errstr() method should not be used to test for errors, use err() for that, because drivers may return 'success with information' or warning messages via errstr() for methods that have not 'failed'.
エラーのテストにはerrstr()メソッドを使用しないでください。 エラーのテストにはerr()を使用してください。 これは、「失敗」していないメソッドに対して、ドライバがerrstr()を介して「情報付きの成功」または警告メッセージを返す可能性があるためです。 (TBR)
See "set_err" for more information.
さらなる情報については "set_err" を参照してください。
state¶
$str = $h->state;
Returns a state code in the standard SQLSTATE five character format. Note that the specific success code 00000 is translated to any empty string (false). If the driver does not support SQLSTATE (and most don't), then state() will return S1000 (General Error) for all errors.
エラーコードを標準の SQLSTATE の 5 文字形式で返します。 ある正常コード 00000 は、空文字列(偽)に変換されてしまうことに 注意してください。 もしドライバが SQLSTATE に対応していなければ(ほとんどが 対応していないのですが)、state() はすべてのエラーについて S1000(一般エラー)を返します。
The driver is free to return any value via state, e.g., warning codes, even if it has not declared an error by returning a true value via the "err" method described above.
ドライバは state でどのような値を返すことも自由です; 例えば 警告コード; 上記の "err" メソッドを介して真の値を返すことにより 宣言されるエラーでなかったとしても。
The state() method should not be used to test for errors, use err() for that, because drivers may return a 'success with information' or warning state code via state() for methods that have not 'failed'.
state()メソッドはエラーのテストには使用しないでください。 err()を使用してください。 これは、ドライバが'情報付きの成功'を返す場合や、'失敗'していないメソッドに対してstate()を介して警告状態コードを返す場合があるためです。 (TBR)
set_err¶
$rv = $h->set_err($err, $errstr);
$rv = $h->set_err($err, $errstr, $state);
$rv = $h->set_err($err, $errstr, $state, $method);
$rv = $h->set_err($err, $errstr, $state, $method, $rv);
Set the err, errstr, and state values for the handle. This method is typically only used by DBI drivers and DBI subclasses.
ハンドルのための err, errstr, state の値を設定します。 このメソッドは典型的には DBI ドライバと DBI サブクラスでのみ使用されます。
If the "HandleSetErr" attribute holds a reference to a subroutine it is called first. The subroutine can alter the $err, $errstr, $state, and $method values. See "HandleSetErr" for full details. If the subroutine returns a true value then the handle err, errstr, and state values are not altered and set_err() returns an empty list (it normally returns $rv which defaults to undef, see below).
"HandleSetErr"属性がサブルーチンへの参照を保持している場合、それが最初に呼び出されます。 サブルーチンは、$err、$errstr、$state、および$method値を変更できます。 詳細については、"HandleSetErr"を参照してください。 サブルーチンが真の値を返す場合、ハンドルerr、errstr、およびstate値は変更されず、set_err()は空のリストを返します(通常は$rvを返し、デフォルトはundefです。 以下を参照してください)。 (TBR)
Setting err to a true value indicates an error and will trigger the normal DBI error handling mechanisms, such as RaiseError and HandleError, if they are enabled, when execution returns from the DBI back to the application.
errをtrue値に設定すると、エラーが示され、RaiseErrorやHandleErrorなどの通常のDBIエラー処理メカニズムが有効になっている場合は、DBIからアプリケーションに実行が戻されたときに、これらのメカニズムがトリガーされます。 (TBR)
Setting err to "" indicates an 'information' state, and setting it to "0" indicates a 'warning' state. Setting err to undef also sets errstr to undef, and state to "", irrespective of the values of the $errstr and $state parameters.
errを""に設定すると「情報」状態を示し、"0"に設定すると「警告」状態を示します。 errをundefに設定すると、$errstrおよび$stateパラメータの値に関係なく、errstrがundefに、stateが""に設定されます。 (TBR)
The $method parameter provides an alternate method name for the RaiseError/PrintError/PrintWarn error string instead of the fairly unhelpful 'set_err'.
$methodパラメータは、RaiseError/PrintError/PrintWarnエラー文字列に対して、あまり役に立たない'set_err'ではなく、代替メソッド名を提供します。 (TBR)
The set_err method normally returns undef. The $rv parameter provides an alternate return value.
set_err メソッドは普通は undef を返します。 $rv パラメータは代替となる返り値を提供します。
Some special rules apply if the err or errstr values for the handle are already set...
ハンドルのための err や errstr の値が 既に 設定されている場合は、 いくつかの特別ルールが適用されます…
If errstr is true then: " [err was %s now %s]" is appended if $err is true and err is already true and the new err value differs from the original one. Similarly " [state was %s now %s]" is appended if $state is true and state is already true and the new state value differs from the original one. Finally "\n" and the new $errstr are appended if $errstr differs from the existing errstr value. Obviously the %s's above are replaced by the corresponding values.
errstrがtrueの場合、$errがtrueで、errがすでにtrueで、新しいerr値が元の値と異なる場合は、「 [err was %s now %s]」が追加されます。 同様に、$stateがtrueで、stateがすでにtrueで、新しいstate値が元の値と異なる場合は、「 [state was %s now %s]」が追加されます。 最後に、$errstrが既存のerrstr値と異なる場合は、「\n」と新しい$errstrが追加されます。 明らかに、上記の%sは対応する値に置き換えられます。 (TBR)
The handle err value is set to $err if: $err is true; or handle err value is undef; or $err is defined and the length is greater than the handle err length. The effect is that an 'information' state only overrides undef; a 'warning' overrides undef or 'information', and an 'error' state overrides anything.
$errがtrueの場合、またはハンドルerrの値がundefの場合、または$errが定義されていて、その長さがハンドルerrの長さよりも長い場合、ハンドルerrの値は$errに設定されます。 その結果、'information'状態はundefのみを上書きし、'warning'はundefまたは'information'を上書きし、'error'状態はすべてを上書きします。 (TBR)
The handle state value is set to $state if $state is true and the handle err value was set (by the rules above).
$state が真でハンドルの err 値が (上述のルールにより) 設定されているなら、ハンドルの state の値は $state に設定されます。
Support for warning and information states was added in DBI 1.41.
警告と情報状態の対応は DBI 1.41 で追加されました。
trace¶
$h->trace($trace_settings);
$h->trace($trace_settings, $trace_filename);
$trace_settings = $h->trace;
The trace() method is used to alter the trace settings for a handle (and any future children of that handle). It can also be used to change where the trace output is sent.
trace() メソッドは、ハンドル(およびそのハンドルの将来の子) の トレース設定を変更するのに使われます。 これはまたトレース出力をどこに送るのかを変更するのにも使われます。
There's a similar method, DBI->trace, which sets the global default trace settings.
似たようなメソッドとして DBI->trace があり、これはグローバルな デフォルトトレース設定を設定します。
See the "TRACING" section for full details about the DBI's powerful tracing facilities.
DBI の強力なトレース機能に関する完全な詳細については "TRACING" の章を参照してください。
trace_msg¶
$h->trace_msg($message_text);
$h->trace_msg($message_text, $min_level);
Writes $message_text to the trace file if the trace level is greater than or equal to $min_level (which defaults to 1). Can also be called as DBI->trace_msg($msg).
トレースレベルが $min_level (デフォルトは 1)以上の場合の場合、 $message_text をトレースファイルに書き出します。 DBI->trace_msg($msg) と呼び出すこともできます。
See "TRACING" for more details.
さらなる情報については "TRACING" を参照してください。
func¶
$h->func(@func_arguments, $func_name) or die ...;
The func method can be used to call private non-standard and non-portable methods implemented by the driver. Note that the function name is given as the last argument.
func メソッドにより、ドライバが実装しているプライベートな標準でなく、 移植できないメソッドを呼び出すことができます。 関数名が 最後の 引数で与えられることに注意してください。
It's also important to note that the func() method does not clear a previous error ($DBI::err etc.) and it does not trigger automatic error detection (RaiseError etc.) so you must check the return status and/or $h->err to detect errors.
また、func()メソッドは以前のエラー($DBI::errなど)をクリアせず、自動エラー検出(RaiseErrorなど)をトリガーしないことに注意することも重要です。 エラーを検出するには、リターンステータスや$h->errをチェックする必要があります。 (TBR)
(This method is not directly related to calling stored procedures. Calling stored procedures is currently not defined by the DBI. Some drivers, such as DBD::Oracle, support it in non-portable ways. See driver documentation for more details.)
(このメソッドはストアドプロシージャの呼び出しに、直接は関係していません。 ストアドプロシージャ呼び出しは、いまのところ DBI によって定義されていません。 DBD::Oracle のようにいくつかのドライバが移植できない形でサポートしています。 詳細についてはドライバのドキュメントをご覧ください。)
See also install_method() in DBI::DBD for how you can avoid needing to use func() and gain direct access to driver-private methods.
func() の使用を避けて、ドライバ固有のメソッドに直接アクセスする 方法については DBI::DBD の install_method() も参照してください。
can¶
$is_implemented = $h->can($method_name);
Returns true if $method_name is implemented by the driver or a default method is provided by the DBI. It returns false where a driver hasn't implemented a method and the default method is provided by the DBI is just an empty stub.
$method_name がドライバによって実装されているか、デフォルトメソッドが DBI によって提供されているなら真を返します。 ドライバがこのメソッドを実装しておらず、DBI によって提供されている デフォルトメソッドが空のスタブである場合は偽を返します。
parse_trace_flags¶
$trace_settings_integer = $h->parse_trace_flags($trace_settings);
Parses a string containing trace settings and returns the corresponding integer value used internally by the DBI and drivers.
トレース設定を含む文字列をパースして、DBI とドライバで内部で使用されている 対応する整数値を返します。
The $trace_settings argument is a string containing a trace level between 0 and 15 and/or trace flag names separated by vertical bar ("|") or comma (",") characters. For example: "SQL|3|foo".
$trace_settings 引数は縦棒 ("|") またはカンマ (",") 文字で区切られた、 0 から 15 のトレースレベルやトレースフラグ名からなる文字列です。 例: "SQL|3|foo"。
It uses the parse_trace_flag() method, described below, to process the individual trace flag names.
これは個々のトレースフラグ名を処理するために後述する parse_trace_flag() メソッドを使います。
The parse_trace_flags() method was added in DBI 1.42.
parse_trace_flags() メソッドは DBI 1.42 で追加されました。
parse_trace_flag¶
$bit_flag = $h->parse_trace_flag($trace_flag_name);
Returns the bit flag corresponding to the trace flag name in $trace_flag_name. Drivers are expected to override this method and check if $trace_flag_name is a driver specific trace flags and, if not, then call the DBI's default parse_trace_flag().
$trace_flag_name のトレースフラグ名に対応するビットフラグを返します。 ドライバはこのメソッドをオーバーライドして、$trace_flag_name が ドライバ固有のフラグかどうかをチェックし、そうでなければ DBI の デフォルトの parse_trace_flag() を呼び出すことを想定されています。
The parse_trace_flag() method was added in DBI 1.42.
parse_trace_flag() メソッドは DBI 1.42 で追加されました。
private_attribute_info¶
$hash_ref = $h->private_attribute_info();
Returns a reference to a hash whose keys are the names of driver-private handle attributes available for the kind of handle (driver, database, statement) that the method was called on.
メソッドが呼び出されたハンドルの種類(ドライバ、データベース、文)で 利用可能なドライバ固有のハンドル属性の名前をキーとしたハッシュへの リファレンスを返します。
For example, the return value when called with a DBD::Sybase $dbh could look like this:
例えば、DBD::Sybase $dbh で呼び出したときの返り値は以下のようになります:
{
syb_dynamic_supported => undef,
syb_oc_version => undef,
syb_server_version => undef,
syb_server_version_string => undef,
}
and when called with a DBD::Sybase $sth they could look like this:
そして DBD::Sybase $sth で呼び出したときは以下のようになります:
{
syb_types => undef,
syb_proc_status => undef,
syb_result_type => undef,
}
The values should be undef. Meanings may be assigned to particular values in future.
値は undef であるべきです。 将来特定の値に関する割り当てが行われます。
swap_inner_handle¶
$rc = $h1->swap_inner_handle( $h2 );
$rc = $h1->swap_inner_handle( $h2, $allow_reparent );
Brain transplants for handles. You don't need to know about this unless you want to become a handle surgeon.
ハンドルの脳移植です。 ハンドルの外科医になろうと思っているのでない限りこれについて知る 必要はありません。
A DBI handle is a reference to a tied hash. A tied hash has an inner hash that actually holds the contents. The swap_inner_handle() method swaps the inner hashes between two handles. The $h1 and $h2 handles still point to the same tied hashes, but what those hashes are tied to has been swapped. In effect $h1 becomes $h2 and vice-versa. This is powerful stuff, expect problems. Use with care.
DBI ハンドルは tie されたハッシュへのリファレンスです。 tie されたハッシュは実際に内容を保持している 内部 ハッシュを持っています。 swap_inner_handle() メソッドは二つのハンドルの内部ハッシュを入れ替えます。 $h1 と $h2 のハンドルは同じ tie されたハッシュを示したままですが、 どのハッシュに tie しているかは入れ替わります。 事実上 $h1 は $h2 に なり、逆もまた真なりです。 これは問題もはらんでいる、強力な機能です。 注意して使ってください。
As a small safety measure, the two handles, $h1 and $h2, have to share the same parent unless $allow_reparent is true.
小さな安全性の尺度として、二つのハンドル $h1 と $h2 は、 $allow_reparent が真でない限り同じ親を共有している必要があります。
The swap_inner_handle() method was added in DBI 1.44.
swap_inner_handle() メソッドは DBI 1.44 で追加されました。
Here's a quick kind of 'diagram' as a worked example to help think about what's happening:
以下は、何が起きているかについて考える助けとなる動作する例の 「ダイアグラム」です:
Original state:
dbh1o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh2o -> dbh2i
swap_inner_handle dbh1o with dbh2o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
create new sth from dbh1o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthBo -> sthBi(dbh2i)
swap_inner_handle sthAo with sthBo:
dbh2o -> dbh1i
sthBo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthAo -> sthBi(dbh2i)
visit_child_handles¶
$h->visit_child_handles( $coderef );
$h->visit_child_handles( $coderef, $info );
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.
$coderef はサブルーチンへのリファレンスで、$info は任意の値であり、 もし未定義ならデフォルトはからハッシュへのリファレンスとなります。 $info を返します。
For each child handle of $h, if any, $coderef is invoked as:
子ハンドルがあれば、各ハンドル $h 毎に、$coderef は以下のようにして 起動されます:
$coderef->($child_handle, $info);
If the execution of $coderef returns a true value then visit_child_handles is called on that child handle and passed the returned value as $info.
$coderef の実行によって真の値が返されると、"visit_child_handles" が 子ハンドルに呼び出され、返された値を $info として渡します。
For example:
例えば:
# count database connections with names (DSN) matching a pattern
my $connections = 0;
$dbh->{Driver}->visit_child_handles(sub {
my ($h, $info) = @_;
++$connections if $h->{Name} =~ /foo/;
return 0; # don't visit kids
})
See also "visit_handles".
"visit_handles" も参照してください。
全てのハンドルに共通の属性¶
These attributes are common to all types of DBI handles.
これらの属性はDBIの全種類のハンドルについて共通です。
Some attributes are inherited by child handles. That is, the value of an inherited attribute in a newly created statement handle is the same as the value in the parent database handle. Changes to attributes in the new statement handle do not affect the parent database handle and changes to the database handle do not affect existing statement handles, only future ones.
属性によっては、子供に継承されるものもあります。つまり新しく作られる 文ハンドルでの継承される属性の値は、その親となる データベースハンドルでの値と同じになります。 新しい文ハンドルでの属性を変更しても親のデータベースハンドルには 影響を与えませんし、データベースハンドルの属性を変更しても、 既存の文ハンドルには影響を与えません。 新しく作られるものだけです。
Attempting to set or get the value of an unknown attribute generates a warning, except for private driver specific attributes (which all have names starting with a lowercase letter).
ドライバ特有のプライベートな属性(これらの名前は小文字ではじまります)を 除いては、決められていない属性を設定あるいは取得しようとすると 警告が発生します。
Example:
例:
$h->{AttributeName} = ...; # set/write
... = $h->{AttributeName}; # get/read
Warn (boolean, inherited)¶
The Warn attribute enables useful warnings for certain bad practices. It is enabled by default and should only be disabled in rare circumstances. Since warnings are generated using the Perl warn function, they can be intercepted using the Perl $SIG{__WARN__} hook.
Warn 属性はある種のよくない実践に対する有効な警告を有効にします。 デフォルトでは有効になっています。 これはデフォルトで有効になっていて、特殊な状況でのみ無効にするべきです。 警告は Perl の warn 関数を使って生成されるので、Perl の $SIG{__WARN__} フックを使って、割り込むことが可能です。
The Warn attribute is not related to the PrintWarn attribute.
Warn 属性は PrintWarn 属性とは関係ありません。
Active (boolean, read-only)¶
The Active attribute is true if the handle object is "active". This is rarely used in applications. The exact meaning of active is somewhat vague at the moment. For a database handle it typically means that the handle is connected to a database ($dbh->disconnect sets Active off). For a statement handle it typically means that the handle is a SELECT that may have more data to fetch. (Fetching all the data or calling $sth->finish sets Active off.)
Active 属性は、ハンドルオブジェクトが生きている("Active")であれば 真になります。 アプリケーションで使われることはまずありません。 "Active"の正確な意味は、その時点によって若干違ってきます。 データベースハンドルにとっては、普通そのハンドルがデータベースに 接続されていることを意味します。 ($dbh->disconnect は Active をオフにします)。 文ハンドルにとって典型的なものは、まだ取り出せるデータが 存在するであろう SELECT であることを意味します。 (すべてのデータを取り出してしまうか、 $sth->finish を実行すると Active をオフに設定します)。
Executed (boolean)¶
The Executed attribute is true if the handle object has been "executed". Currently only the $dbh do() method and the $sth execute(), execute_array(), and execute_for_fetch() methods set the Executed attribute.
Executed 属性は、ハンドルオブジェクトが「実行された」場合に真になります。 現在のところ、$dbh の do() メソッドと、$sth の execute(), execute_array(), execute_for_fetch() メソッドが Executed 属性を設定します。
When it's set on a handle it is also set on the parent handle at the same time. So calling execute() on a $sth also sets the Executed attribute on the parent $dbh.
ハンドルに設定すると、同時に親ハンドルにも設定されます。 したがって、$sthでexecute()を呼び出すと、親の$dbhにもExecuted属性が設定されます。 (TBR)
The Executed attribute for a database handle is cleared by the commit() and rollback() methods (even if they fail). The Executed attribute of a statement handle is not cleared by the DBI under any circumstances and so acts as a permanent record of whether the statement handle was ever used.
データベースハンドルのExecuted属性は、(失敗した場合でも)commit()およびrollback()メソッドによってクリアされます。 文ハンドルのExecuted属性は、どのような状況でもDBIによってクリアされないため、文ハンドルが使用されたことがあるかどうかを示す永続的なレコードとして機能します。 (TBR)
The Executed attribute was added in DBI 1.41.
Executed 属性は DBI 1.41 で追加されました。
Kids (integer, read-only)¶
For a driver handle, Kids is the number of currently existing database handles that were created from that driver handle. For a database handle, Kids is the number of currently existing statement handles that were created from that database handle. For a statement handle, the value is zero.
ドライバハンドルの場合、Kids はそのドライバハンドルから作られ、現在 存在しているデータベースハンドルの数になります。 データベースハンドルの場合、Kids はそのデータベースハンドルから作られ、 現在存在している文ハンドルの数になります。 文ハンドルの場合、値は 0 です。
ActiveKids (integer, read-only)¶
Like Kids, but only counting those that are Active (as above).
Kids と同様ですが、Active なものだけをカウントします(上記参照)。
CachedKids (hash ref)¶
For a database handle, CachedKids returns a reference to the cache (hash) of statement handles created by the "prepare_cached" method. For a driver handle, returns a reference to the cache (hash) of database handles created by the "connect_cached" method.
データベース・ハンドルの場合、CachedKids は "prepare_cached" メソッドにより生成された文ハンドルの キャッシュ(ハッシュ)へのリファレンスを返します。 ドライバハンドルの場合、"connect_cached" メソッドにより作成された 文ハンドルのキャッシュ(ハッシュ)へのリファレンスを返します。
Type (scalar, read-only)¶
The Type attribute identifies the type of a DBI handle. Returns "dr" for driver handles, "db" for database handles and "st" for statement handles.
Type 属性は DBI ハンドルの種類を識別します。 ドライバハンドルの場合は "dr" を、データベースハンドルの場合は "db" を、 文ハンドルの場合は "st" を返します。
ChildHandles (array ref)¶
The ChildHandles attribute contains a reference to an array of all the handles created by this handle which are still accessible. The contents of the array are weak-refs and will become undef when the handle goes out of scope.
ChildHandles 属性は、このハンドルによって作られてまだアクセス可能な 全てのハンドルの配列へのリファレンスを含みます。 配列の内容は弱い参照で、ハンドルがスコープ外に出ると undef になります。
ChildHandles returns undef if your perl version does not support weak references (check the Scalar::Util module). The referenced array returned should be treated as read-only.
Perlのバージョンが弱い参照をサポートしていない場合、ChildHandlesはundefを返します(Scalar::Utilモジュールをチェックしてください)。 返された参照配列は読み取り専用として扱われます。 (TBR)
For example, to enumerate all driver handles, database handles and statement handles:
例えば、全てのドライバハンドル、データベースハンドル、文ハンドルを 数え上げるには:
sub show_child_handles {
my ($h, $level) = @_;
printf "%sh %s %s\n", $h->{Type}, "\t" x $level, $h;
show_child_handles($_, $level + 1)
for (grep { defined } @{$h->{ChildHandles}});
}
my %drivers = DBI->installed_drivers();
show_child_handles($_, 0) for (values %drivers);
CompatMode (boolean, inherited)¶
The CompatMode attribute is used by emulation layers (such as Oraperl) to enable compatible behaviour in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally set by application code.
CompatMode 属性は(Oraperl のような)エミュレーション層で使われ、 このハンドルのために元になっているドライバ(例えば DBD::Oracle)で 互換性のある動きをすることを可能にします。 アプリケーションプログラムでは通常使われることはありません。
It also has the effect of disabling the 'quick FETCH' of attribute values from the handles attribute cache. So all attribute values are handled by the drivers own FETCH method. This makes them slightly slower but is useful for special-purpose drivers like DBD::Multiplex.
また、ハンドル属性キャッシュからの属性値の「クイックFETCH」を無効にする効果もあります。 したがって、すべての属性値はドライバ独自のFETCHメソッドによって処理されます。 これにより、それらは少し遅くなりますが、DBD::Multiplexのような特別な目的のドライバには有用です。 (TBR)
InactiveDestroy (boolean)¶
The default value, false, means a handle will be fully destroyed as normal when the last reference to it is removed, just as you'd expect.
デフォルト値である偽は、予想している通り、ハンドルへの最後のリファレンスが 削除されると通常通り完全に破壊されることを意味します。
If set true then the handle will be treated by the DESTROY as if it was no longer Active, and so the database engine related effects of DESTROYing a handle will be skipped.
trueに設定すると、ハンドルはDESTROYによってアクティブではなくなったものとして処理されるため、ハンドルをDESTROYingするdatabase engine関連の効果はスキップされます。 (TBR)
Think of the name as meaning 'treat the handle as not-Active in the DESTROY method'.
名前は「ハンドルを、DESTROY メソッド内では非アクティブとして扱う」という 意味です。
For a database handle, this attribute does not disable an explicit call to the disconnect method, only the implicit call from DESTROY that happens if the handle is still marked as Active.
データベースハンドルにとっては、この属性は disconnect メソッドの 明示的な 呼び出しを無効にせず、ハンドルに Active とマークされている ときに DESTROY から暗黙の呼び出しだけを無効にします。
This attribute is specifically designed for use in Unix applications that "fork" child processes. Either the parent or the child process, but not both, should set InactiveDestroy true on all their shared handles. (Note that some databases, including Oracle, don't support passing a database connection across a fork.)
この属性は、特に子プロセスを "fork" する UNIX アプリケーションでの 使用について設計されています。 親と子の両方ではなくどちらか片方だけが、共有しているハンドルのすべてに InactiveDestroy を設定するべきです。 (Oracle を含めて、いくつかのドライバはデータベース接続を fork をまたがって 渡すことをサポートしていないことに注意してください。)
To help tracing applications using fork the process id is shown in the trace log whenever a DBI or handle trace() method is called. The process id also shown for every method call if the DBI trace level (not handle trace level) is set high enough to show the trace from the DBI's method dispatcher, e.g. >= 9.
forkを使用したアプリケーションのトレースを支援するために、DBIまたはhandle trace()メソッドが呼び出されるたびに、プロセスIDがトレースログに表示されます。 DBIトレースレベル(ハンドルトレースレベルではない)がDBIのメソッドディスパッチャからのトレースを表示するのに十分な高さに設定されている場合(>=9など)、everyメソッドコールに対してもプロセスIDが表示されます。 (TBR)
PrintWarn (boolean, inherited)¶
The PrintWarn attribute controls the printing of warnings recorded by the driver. When set to a true value the DBI will check method calls to see if a warning condition has been set. If so, the DBI will effectively do a warn("$class $method warning: $DBI::errstr") where $class is the driver class and $method is the name of the method which failed. E.g.,
PrintWarn 属性は、ドライバによって記録された警告の表示を制御します。 真の値に設定されると、 警告条件が設定されたかどうかメソッド呼び出しをチェックします。 その場合、DBI は事実上 warn("$class $method warning: $DBI::errstr") を 実行します; ここで $class はドライバクラスで $method は失敗した メソッドの名前です。 例えば:
DBD::Oracle::db execute warning: ... warning text here ...
By default, DBI->connect sets PrintWarn "on" if $^W is true, i.e., perl is running with warnings enabled.
$^W が真なら PrintWarn 属性のデフォルトはオンです; つまり、perl は 警告を有効にして動作します。
If desired, the warnings can be caught and processed using a $SIG{__WARN__} handler or modules like CGI::Carp and CGI::ErrorWrap.
もし望むなら、$SIG{__WARN__} ハンドラまたは CGI::Carp や CGI::ErrorWrap のようなモジュールを使って、警告を捕捉して処理できます。
See also "set_err" for how warnings are recorded and "HandleSetErr" for how to influence it.
警告がどのように記録されるかについては "set_err" も、それがどのように 影響を与えるかについては "HandleSetErr" も参照してください。
Fetching the full details of warnings can require an extra round-trip to the database server for some drivers. In which case the driver may opt to only fetch the full details of warnings if the PrintWarn attribute is true. If PrintWarn is false then these drivers should still indicate the fact that there were warnings by setting the warning string to, for example: "3 warnings".
一部のドライバでは、警告の完全な詳細をフェッチするために、データベースサーバーへの余分なラウンドトリップが必要になる場合があります。 この場合、ドライバは、PrintWarn属性がTRUEの場合にのみ、警告の完全な詳細をフェッチすることを選択できます。 PrintWarnがFALSEの場合でも、これらのドライバは、警告文字列を「3 warnings」などに設定することによって、警告があったことを示す必要があります。 (TBR)
PrintError (boolean, inherited)¶
The PrintError attribute can be used to force errors to generate warnings (using warn) in addition to returning error codes in the normal way. When set "on", any method which results in an error occurring will cause the DBI to effectively do a warn("$class $method failed: $DBI::errstr") where $class is the driver class and $method is the name of the method which failed. E.g.,
PrintError 属性は、エラーが発生したら、通常の方法でエラーコードを 返すことに加えて、(warn を使って)警告を生成するように強制します。 "on"に設定されているとき、なんらかのメソッドがエラーになると、DBI に 事実上 warn("$class $method failed: $DBI::errstr") を実行させます; $class にはドライバクラス、$method には失敗したメソッドが入ります。 例えば
DBD::Oracle::db prepare failed: ... error text here ...
By default, DBI->connect sets PrintError "on".
デフォルトでは、DBI->connect は PrintError を "on" に設定します。
If desired, the warnings can be caught and processed using a $SIG{__WARN__} handler or modules like CGI::Carp and CGI::ErrorWrap.
もし望むなら、$SIG{__WARN__} ハンドラまたは CGI::Carp や CGI::ErrorWrap のようなモジュールを使って、警告を捕捉して処理できます。
RaiseError (boolean, inherited)¶
The RaiseError attribute can be used to force errors to raise exceptions rather than simply return error codes in the normal way. It is "off" by default. When set "on", any method which results in an error will cause the DBI to effectively do a die("$class $method failed: $DBI::errstr"), where $class is the driver class and $method is the name of the method that failed. E.g.,
RaiseError 属性はエラー発生時に通常通り単にエラーコードを返すのではなく、 例外を発生させるために使われます。 デフォルトは"off"です。 "on" に設定されているとき、なんらかのメソッドでエラーになると、DBI に 事実上 die("$class $method failed: $DBI::errstr") を実行させます; $class にはドライバクラス、$method には失敗したメソッドが入ります。 例えば
DBD::Oracle::db prepare failed: ... error text here ...
If you turn RaiseError on then you'd normally turn PrintError off. If PrintError is also on, then the PrintError is done first (naturally).
RaiseError をオンにすると、普通 PrintError はオフにします。 PrintError もオンにすると、(自然なように) PrintError がまず 実行されます。
Typically RaiseError is used in conjunction with eval { ... } to catch the exception that's been thrown and followed by an if ($@) { ... } block to handle the caught exception. For example:
通常、RaiseErrorは、スローされた例外をキャッチするためにeval{.}とともに使用され、その後に、キャッチされた例外を処理するためのif($@){.}ブロックが続きます。 次に例を示します。 (TBR)
eval {
...
$sth->execute();
...
};
if ($@) {
# $sth->err and $DBI::err will be true if error was from DBI
warn $@; # print the error
... # do whatever you need to deal with the error
}
In that eval block the $DBI::lasth variable can be useful for diagnosis and reporting if you can't be sure which handle triggered the error. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
このevalブロックでは、$DBI::lasth変数を使用すると、エラーの原因となったハンドルを特定できない場合に、診断やレポート作成に役立ちます。 たとえば、$DBI::lasth->{Type}や$DBI::lasth->{Statement}などです。 (TBR)
See also "Transactions".
"Transactions" も参照してください。
If you want to temporarily turn RaiseError off (inside a library function that is likely to fail, for example), the recommended way is like this:
一時的に RaiseError をオフに切り替えたいのであれば(例えば障害が 発生しやすいライブラリ関数の内部など)、以下のようにすることをお勧めします:
{
local $h->{RaiseError}; # localize and turn off for this block
...
}
The original value will automatically and reliably be restored by Perl, regardless of how the block is exited. The same logic applies to other attributes, including PrintError.
そのブロックからどのように抜けたのかは関係なく、元の値は自動的に、信頼性を 持って Perl により保存されます。 PrintError も含めて、他の属性についても同じロジックが適用されます。
HandleError (code ref, inherited)¶
The HandleError attribute can be used to provide your own alternative behaviour in case of errors. If set to a reference to a subroutine then that subroutine is called when an error is detected (at the same point that RaiseError and PrintError are handled).
HandleError 属性は、エラー時に別の独自の振る舞いを提供するために 使われます。 サブルーチンへのリファレンスを設定すると、 エラーが検出されたときに (RaiseError と PrintError が 扱われるのと同じ時点で) そのサブルーチンが呼び出されます。
The subroutine is called with three parameters: the error message string that RaiseError and PrintError would use, the DBI handle being used, and the first value being returned by the method that failed (typically undef).
このサブルーチンは、RaiseErrorおよびPrintErrorで使用されるエラーメッセージ文字列、使用されるDBIハンドル、および失敗したメソッドによって返される最初の値(通常はundef)の3つのパラメータを指定して呼び出されます。 (TBR)
If the subroutine returns a false value then the RaiseError and/or PrintError attributes are checked and acted upon as normal.
サブルーチンが偽の値を返すと、RaiseError 属性や PrintError 属性が チェックされ、通常通り動作します。
For example, to die with a full stack trace for any error:
例えば、全てのエラーについて完全なスタックトレースと共に die させるには:
use Carp;
$h->{HandleError} = sub { confess(shift) };
Or to turn errors into exceptions:
またはエラーを例外に変換するには:
use Exception; # or your own favourite exception module
$h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
It is possible to 'stack' multiple HandleError handlers by using closures:
クロージャを使うことで複数の HandleError ハンドラを「スタック」させることが できます:
sub your_subroutine {
my $previous_handler = $h->{HandleError};
$h->{HandleError} = sub {
return 1 if $previous_handler and &$previous_handler(@_);
... your code here ...
};
}
Using a my inside a subroutine to store the previous HandleError value is important. See perlsub and perlref for more information about closures.
サブルーチン内でmyを使用して、前のHandleError値を格納することは重要です。 クロージャーの詳細については、perlsubおよびperlrefを参照してください。 (TBR)
It is possible for HandleError to alter the error message that will be used by RaiseError and PrintError if it returns false. It can do that by altering the value of $_[0]. This example appends a stack trace to all errors and, unlike the previous example using Carp::confess, this will work PrintError as well as RaiseError:
HandleErrorがfalseを返す場合は、RaiseErrorおよびPrintErrorで使用されるエラーメッセージをHandleErrorで変更できます。 これは、$_[0]の値を変更することで可能になります。 この例では、すべてのエラーにスタックトレースを追加します。 Carp::analを使用した前述の例とは異なり、これはPrintErrorおよびRaiseErrorでも機能します: (TBR)
$h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; };
It is also possible for HandleError to hide an error, to a limited degree, by using "set_err" to reset $DBI::err and $DBI::errstr, and altering the return value of the failed method. For example:
HandleErrorでは、"set_err"を使用して$DBI::errおよび$DBI::errstrをリセットし、失敗したメソッドの戻り値を変更することによって、限られた程度でエラーを非表示にすることもできます。 次に例を示します。 (TBR)
$h->{HandleError} = sub {
return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/;
return 0 unless $_[1]->err == 1234; # the error to 'hide'
$h->set_err(undef,undef); # turn off the error
$_[2] = [ ... ]; # supply alternative return value
return 1;
};
This only works for methods which return a single value and is hard to make reliable (avoiding infinite loops, for example) and so isn't recommended for general use! If you find a good use for it then please let me know.
これは、単一の値を返すメソッドに対してのみ動作し、信頼性を確保するのが難しい(例えば、無限ループを回避する)ため、一般的な使用には推奨されません!もし、goodの使い方を見つけたら、教えてください。 (TBR)
HandleSetErr (code ref, inherited)¶
The HandleSetErr attribute can be used to intercept the setting of handle err, errstr, and state values. If set to a reference to a subroutine then that subroutine is called whenever set_err() is called, typically by the driver or a subclass.
HandleSetErr 属性は、err, errstr, state の値を扱う設定に 割り込むために使われます。 サブルーチンへのリファレンスを設定すると、 (典型的にはドライバやサブクラスから) set_err() が呼び出されたときにこのサブルーチンが呼び出されます。
The subroutine is called with five arguments, the first five that were passed to set_err(): the handle, the err, errstr, and state values being set, and the method name. These can be altered by changing the values in the @_ array. The return value affects set_err() behaviour, see "set_err" for details.
サブルーチンは、set_err()に渡された最初の5つの引数(ハンドル、設定されたerr、errstr、およびstate値、およびメソッド名)を使用して呼び出されます。 これらは@_arrayの値を変更することで変更できます。 戻り値はset_err()の動作に影響します。 詳細については"set_err"を参照してください。 (TBR)
It is possible to 'stack' multiple HandleSetErr handlers by using closures. See "HandleError" for an example.
クロージャを使うことで複数の HandleSetErr ハンドラを 「スタック」させることができます: 例については "HandleError" を参照してください。
The HandleSetErr and HandleError subroutines differ in subtle but significant ways. HandleError is only invoked at the point where the DBI is about to return to the application with err set true. It's not invoked by the failure of a method that's been called by another DBI method. HandleSetErr, on the other hand, is called whenever set_err() is called with a defined err value, even if false. So it's not just for errors, despite the name, but also warn and info states. The set_err() method, and thus HandleSetErr, may be called multiple times within a method and is usually invoked from deep within driver code.
HandleSetErrとHandleErrorのサブルーチンは、微妙ですが重要な点で異なります。 HandleErrorは、errがtrueに設定された状態でDBIがアプリケーションに戻ろうとする時点でのみ呼び出されます。 別のDBIメソッドによって呼び出されたメソッドの失敗によって呼び出されることはありません。 一方、HandleSetErrは、定義されたerr値でset_err()が呼び出されるたびに、falseであっても呼び出されます。 したがって、名前にかかわらずエラーに対してだけでなく、警告状態や情報状態に対しても呼び出されます。 set_err()メソッド、したがってHandleSetErrは、メソッド内で複数回呼び出される可能性があり、通常はドライバコードの奥深くから呼び出されます。 (TBR)
In theory a driver can use the return value from HandleSetErr via set_err() to decide whether to continue or not. If set_err() returns an empty list, indicating that the HandleSetErr code has 'handled' the 'error', the driver could then continue instead of failing (if that's a reasonable thing to do). This isn't excepted to be common and any such cases should be clearly marked in the driver documentation and discussed on the dbi-dev mailing list.
理論的には、ドライバはset_err()を介してHandleSetErrからの戻り値を使用して、続行するかどうかを決定できます。 set_err()が空のリストを返し、HandleSetErrコードが「エラー」を「処理した」ことを示した場合、ドライバは失敗するのではなく続行できます(それが合理的なことである場合)。 これは一般的であることを除外するものではなく、そのような場合はドライバの文書で明確にマークされ、dbi-devメーリングリストで議論されるべきです。 (TBR)
The HandleSetErr attribute was added in DBI 1.41.
HandleSetErr 属性は DBI 1.41 で追加されました。
ErrCount (unsigned integer)¶
The ErrCount attribute is incremented whenever the set_err() method records an error. It isn't incremented by warnings or information states. It is not reset by the DBI at any time.
ErrCount 属性は、set_err() メソッドがエラーを記録する毎に インクリメントされます。 これは警告や情報表示ではインクリメントされません。 これは DBI によってリセットされることはありません。
The ErrCount attribute was added in DBI 1.41. Older drivers may not have been updated to use set_err() to record errors and so this attribute may not be incremented when using them.
ErrCount 属性は DBI 1.41 で追加されました。 より古いドライバはエラーを記録するために set_err() を使うときに 更新されないので、この属性はこれらを使ったときに インクリメントされないかも知れません。
ShowErrorStatement (boolean, inherited)¶
The ShowErrorStatement attribute can be used to cause the relevant Statement text to be appended to the error messages generated by the RaiseError, PrintError, and PrintWarn attributes. Only applies to errors on statement handles plus the prepare(), do(), and the various select*() database handle methods. (The exact format of the appended text is subject to change.)
ShowErrorStatement 属性は、 RaiseError, PrintError, PrintWarn 属性によって 生成されたエラーメッセージに追加される、関連する Statement のテキストを 追加するために使われます。 文ハンドルのエラーに加えて、prepare(), do() および様々な select*() データベースハンドルメソッドのエラーにのみ適用されます。 (追加されるテキストの正確な形式は変更されることがあります。)
If $h->{ParamValues} returns a hash reference of parameter (placeholder) values then those are formatted and appended to the end of the Statement text in the error message.
$h->{ParamValues} がパラメータ(プレースホルダ)の値の ハッシュリファレンスを返す場合、これらはフォーマットされて エラーメッセージの Statement のテキストの末尾に追加されます。
TraceLevel (integer, inherited)¶
The TraceLevel attribute can be used as an alternative to the "trace" method to set the DBI trace level and trace flags for a specific handle. See "TRACING" for more details.
TraceLevel 属性は、DBI トレースレベルと特定のハンドルのトレースフラグを 設定するための "trace" メソッドの代わりとして使えます。 さらなる詳細については "TRACING" を参照してください。
The TraceLevel attribute is especially useful combined with local to alter the trace settings for just a single block of code.
TraceLevel 属性は、特定の一つのブロックのコードでだけトレース設定を 変更するために local を組み合わせると特に便利です。
FetchHashKeyName (string, inherited)¶
The FetchHashKeyName attribute is used to specify whether the fetchrow_hashref() method should perform case conversion on the field names used for the hash keys. For historical reasons it defaults to 'NAME' but it is recommended to set it to 'NAME_lc' (convert to lower case) or 'NAME_uc' (convert to upper case) according to your preference. It can only be set for driver and database handles. For statement handles the value is frozen when prepare() is called.
FetchHashKeyName属性は、fetchrow_uc()メソッドがハッシュキーに使用されるフィールド名に対して大文字と小文字の変換を実行するかどうかを指定するために使用されます。 歴史的な理由により、デフォルトは'NAME'ですが、好みに応じて'NAME_lc'(小文字に変換)または'NAME_uc'(大文字に変換)に設定することをお薦めします。 これは、ドライバおよびデータベースハンドルに対してのみ設定できます。 ステートメントハンドルの場合、prepare()が呼び出されると値が凍結されます。 hashref (TBR)
ChopBlanks (boolean, inherited)¶
The ChopBlanks attribute can be used to control the trimming of trailing space characters from fixed width character (CHAR) fields. No other field types are affected, even where field values have trailing spaces.
ChopBlanks 属性は固定長文字列(CHAR)フィールドから末尾の空白を 取り除くことを制御するために使われます。 他のフィールドタイプには、例え末尾に空白がついていても、影響を与えません。
The default is false (although it is possible that the default may change). Applications that need specific behaviour should set the attribute as needed.
デフォルトは偽です。 (しかしデフォルトが変更される可能性があります)。 特定の動きが必要なアプリケーションは、この属性を必要な値に設定します。
Drivers are not required to support this attribute, but any driver which does not support it must arrange to return undef as the attribute value.
ドライバはこの属性をサポートしなければならないわけではありません。 しかしサポートしていないドライバはこの属性の値として undef を 返すようにしなければなりません。
LongReadLen (unsigned integer, inherited)¶
The LongReadLen attribute may be used to control the maximum length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will read from the database automatically when it fetches each row of data.
LongReadLen 属性は、データ行を取り出す際に、ドライバがデータベースから 自動的に読みこむ「長い」フィールド(LONG, BLOB, CLOB, MEMO など)の 最大長を制御するために使われます。
The LongReadLen attribute only relates to fetching and reading long values; it is not involved in inserting or updating them.
LongReadLen 属性は「長い」値の取り出しと読みこみにだけ関連します; 挿入や更新のときには関係しません。
A value of 0 means not to automatically fetch any long data. Drivers may return undef or an empty string for long fields when LongReadLen is 0.
値が 0 は、「長い」データは自動的に取り出されないことを意味します。 LongReadLen が 0 のとき、「長い」フィールドの値は undef または 空文字列になります。
The default is typically 0 (zero) or 80 bytes but may vary between drivers. Applications fetching long fields should set this value to slightly larger than the longest long field value to be fetched.
デフォルトは通常 0 または 80 バイトですが、ドライバによって違うかもしれません。 「長い」フィールドを取り出すアプリケーションは、取り出される 「長い」フィールドの最大長よりもちょっとだけ大きい値を、 この値に設定しなければなりません。
Some databases return some long types encoded as pairs of hex digits. For these types, LongReadLen relates to the underlying data length and not the doubled-up length of the encoded string.
ある種のデータベースは「長い」タイプを 16 進のペアでエンコードして返す 場合があります。 これらのタイプについては、LongReadLen はエンコードされた文字列の 2 倍になった長さではなく、基になっているデータ長に関係します。
Changing the value of LongReadLen for a statement handle after it has been prepare'd will typically have no effect, so it's common to set LongReadLen on the $dbh before calling prepare.
既に prepare された後に、文ハンドルの LongReadLen を 変更しても、通常、何も影響を与えません; そのため普通、prepare を呼び出す前に、$dbh に対して LongReadLen を 設定します。
For most drivers the value used here has a direct effect on the memory used by the statement handle while it's active, so don't be too generous. If you can't be sure what value to use you could execute an extra select statement to determine the longest value. For example:
ほとんどのドライバではここに使われる値が有効な文ハンドルによって 使われるメモリに対して直接的な影響を与えることに注意してください。 そのため、あまり気前よくならないようにしてください。 この値の使い方がはっきりとわからないなら、一番長い値を決定するために 追加の select 文を実行できます。 例えば:
$dbh->{LongReadLen} = $dbh->selectrow_array(qq{
SELECT MAX(OCTET_LENGTH(long_column_name))
FROM table WHERE ...
});
$sth = $dbh->prepare(qq{
SELECT long_column_name, ... FROM table WHERE ...
});
You may need to take extra care if the table can be modified between the first select and the second being executed. You may also need to use a different function if OCTET_LENGTH() does not work for long types in your database. For example, for Sybase use DATALENGTH() and for Oracle use LENGTHB().
最初の選択から2番目の選択が実行されるまでの間に表が変更される可能性がある場合は、特に注意する必要があります。 また、OCTET_LENGTH()がデータベースのlong型に対して機能しない場合は、別の関数を使用する必要があります。 たとえば、Sybaseの場合はDATALENGTH()を使用し、Oracleの場合はLENGTHB()を使用します。 (TBR)
See also "LongTruncOk" for information on truncation of long types.
長い型の切り詰めに関する情報については "LongTruncOk" も参照してください。
LongTruncOk (boolean, inherited)¶
The LongTruncOk attribute may be used to control the effect of fetching a long field value which has been truncated (typically because it's longer than the value of the LongReadLen attribute).
LongTruncOk 属性は、(通常は LongReadLen 属性よりも長いために) 切り捨てられる「長い」フィールドの取り出しの影響を制御するために使われます。
By default, LongTruncOk is false and so fetching a long value that needs to be truncated will cause the fetch to fail. (Applications should always be sure to check for errors after a fetch loop in case an error, such as a divide by zero or long field truncation, caused the fetch to terminate prematurely.)
デフォルトでは LongTruncOk は偽です; そのため切り捨てられる必要がある 「長い」値を取り出すと取り出し失敗となります。 (アプリケーションは、エラーの場合、取り出しループの後で、エラーを常に確実に チェックしなければなりません。 0 除算、「長い」フィールドの切り捨てなどによって取り出しが早く 終わってしまうことがあります。)
If a fetch fails due to a long field truncation when LongTruncOk is false, many drivers will allow you to continue fetching further rows.
LongTruncOk が偽のとき、「長い」フィールドにより取り出しが失敗しても、 多くのドライバでは先の行を取り出すことができます。
See also "LongReadLen".
"LongReadLen" も参照してください。
TaintIn (boolean, inherited)¶
If the TaintIn attribute is set to a true value and Perl is running in taint mode (e.g., started with the -T option), then all the arguments to most DBI method calls are checked for being tainted. This may change.
TaintIn属性が真の値に設定され、かつPerlが汚染モードで実行されている場合 (たとえば、-Tオプションで開始された場合)、ほとんどのDBIメソッド呼び出しの すべての引数が汚染されているかどうかがチェックされます。 これは変更される可能性があります。 (TBR)
The attribute defaults to off, even if Perl is in taint mode. See perlsec for more about taint mode. If Perl is not running in taint mode, this attribute has no effect.
Perl が汚染モードであっても、この属性のデフォルトはオフです。 汚染モードについてのさらなる情報は perlsec を参照してください。 Perl が汚染モードで実行されていなければ、これは何も効果がありません。
When fetching data that you trust you can turn off the TaintIn attribute, for that statement handle, for the duration of the fetch loop.
信頼できるデータをフェッチするときには、そのフェッチループの間、 その文ハンドルに対して、TaintIn 属性をオフにできます。
The TaintIn attribute was added in DBI 1.31.
TaintIn 属性は DBI 1.31 で追加されました。
TaintOut (boolean, inherited)¶
If the TaintOut attribute is set to a true value and Perl is running in taint mode (e.g., started with the -T option), then most data fetched from the database is considered tainted. This may change.
TaintOut 属性に真の値が設定され、かつ Perl が汚染(taint)モード (例えば -T オプションで開始されて)で実行されていれば、データベースから 取り出されるすべてのデータは汚染されているとチェックされます。 これは変更されるかもしれません。
The attribute defaults to off, even if Perl is in taint mode. See perlsec for more about taint mode. If Perl is not running in taint mode, this attribute has no effect.
Perl が汚染モードであっても、この属性のデフォルトはオフです。 汚染モードについてのさらなる情報は perlsec を参照してください。 Perl が汚染モードで実行されていなければ、これは何も効果がありません。
When fetching data that you trust you can turn off the TaintOut attribute, for that statement handle, for the duration of the fetch loop.
信頼できるデータを取り出すとき、文ハンドルについて、取り出し ループの間は TaintOut 属性をオフに切り替えることが出来ます。
Currently only fetched data is tainted. It is possible that the results of other DBI method calls, and the value of fetched attributes, may also be tainted in future versions. That change may well break your applications unless you take great care now. If you use DBI Taint mode, please report your experience and any suggestions for changes.
現在は取り出されたデータだけが汚染されているとしています。 将来のバージョンでは他の DBI メソッド呼び出しの結果そして取り出された属性の 値も同様に汚染されているとするかもしれません。 今のうちに細心の注意を払わない限り、その変更はアプリケーションを 壊しかねません。 もし DBI を Taint モードで使うのであれば、変更のためにあなたの経験と提案を 報告してください。
The TaintOut attribute was added in DBI 1.31.
TaintOut 属性は DBI 1.31 で追加されました。
Taint (boolean, inherited)¶
The Taint attribute is a shortcut for "TaintIn" and "TaintOut" (it is also present for backwards compatibility).
Taint 属性は "TaintIn" と "TaintOut" へのショートカットです (これはまた後方互換性のためにも存在しています)。
Setting this attribute sets both "TaintIn" and "TaintOut", and retrieving it returns a true value if and only if "TaintIn" and "TaintOut" are both set to true values.
この属性を設定すると、"TaintIn"と"TaintOut"の両方が設定されます。 この属性を取得すると、"TaintIn"と"TaintOut"の両方がtrue値に設定されている場合にのみtrue値が戻されます。 (TBR)
Profile (inherited)¶
The Profile attribute enables the collection and reporting of method call timing statistics. See the DBI::Profile module documentation for much more detail.
Profile 属性は、メソッド呼び出しタイミング統計の収集と報告を 有効にします。 非常に 細かな詳細については DBI::Profile モジュールの文書を 参照してください。
The Profile attribute was added in DBI 1.24.
Profile 属性は DBI 1.24 で追加されました。
ReadOnly (boolean, inherited)¶
An application can set the ReadOnly attribute of a handle to a true value to indicate that it will not be attempting to make any changes using that handle or any children of it.
アプリケーションは、ハンドルのReadOnly属性をtrue値に設定して、そのハンドルまたはその子を使用して変更を試みないことを示すことができます。 (TBR)
Note that the exact definition of 'read only' is rather fuzzy. For more details see the documentation for the driver you're using.
「読み込み専用」の正確な定義はややあいまいであることに注意してください。 さらなる詳細については使っているドライバの文書を参照してください。
If the driver can make the handle truly read-only then it should (unless doing so would have unpleasant side effect, like changing the consistency level from per-statement to per-session). Otherwise the attribute is simply advisory.
ドライバがハンドルを本当に読み取り専用にできるのであれば、そうすべきです(ただし、整合性レベルを文単位からセッション単位に変更するなど、不快な副作用が発生する場合は除きます)。 そうでない場合は、この属性は単なるアドバイスです。 (TBR)
A driver can set the ReadOnly attribute itself to indicate that the data it is connected to cannot be changed for some reason.
ドライバは、何らかの理由で変更できないものに接続しているデータであることを 示すために自らの ReadOnly 属性を設定できます。
Library modules and proxy drivers can use the attribute to influence their behavior. For example, the DBD::Gofer driver considers the ReadOnly attribute when making a decision about whether to retry an operation that failed.
ライブラリモジュールおよびプロキシドライバは、この属性を使用して動作に影響を与えることができます。 たとえば、DBD::Goferドライバは、失敗した操作を再試行するかどうかを決定するときに、ReadOnly属性を考慮します。 (TBR)
The attribute should be set to 1 or 0 (or undef). Other values are reserved.
属性は 1 または 0 (または undef)に設定されるべきです。 その他の値は予約されています。
Callbacks (hash ref)¶
The DBI callback mechanism lets you intercept, and optionally replace, any method call on a DBI handle. At the extreme, it lets you become a puppet master, deceiving the application in any way you want.
DBIコールバックメカニズムを使用すると、DBIハンドル上の任意のメソッドコールをインターセプトし、オプションで置き換えることができます。 極端な場合には、それはあなたが操り人形のマスターになり、あなたが望む方法でアプリケーションを欺くことを可能にします。 (TBR)
The Callbacks attribute is a hash reference where the keys are DBI method names and the values are code references. For each key naming a method, the DBI will execute the associated code reference before executing the method.
Callbacks属性はハッシュ参照で、キーはDBIメソッド名、値はコード参照です。 メソッドを指定する各キーに対して、DBIはメソッドを実行する前に関連付けられたコード参照を実行します。 (TBR)
The arguments to the code reference will be the same as to the method, including the invocant (a database handle or statement handle). For example, say that to callback to some code on a call to prepare():
コード参照の引数は、invocant(データベースハンドルまたはステートメントハンドル)を含めて、メソッドの引数と同じになります。 たとえば、prepare()の呼び出しでコードにコールバックするには、次のようにします。 (TBR)
$dbh->{Callbacks} = {
prepare => sub {
my ($dbh, $query, $attrs) = @_;
print "Preparing q{$query}\n"
},
};
The callback would then be executed when you called the prepare() method:
prepare() メソッドを呼び出したときに、コールバックが実行されます:
$dbh->prepare('SELECT 1');
And the output of course would be:
そして出力はもちろん以下のようになります:
Preparing q{SELECT 1}
Because callbacks are executed before the methods they're associated with, you can modify the arguments before they're passed on to the method call. For example, to make sure that all calls to prepare() are immediately prepared by DBD::Pg, add a callback that makes sure that the pg_prepare_now attribute is always set:
コールバックは関連付けられたメソッドの<前>に実行されるため、メソッド呼び出しに渡される前に引数を変更できます。 例えば、prepare()へのすべての呼び出しがDBD::Pgによって即座に準備されるようにするには、pg_prepare_now属性が常に設定されるようにするコールバックを追加します。 (TBR)
my $dbh = DBI->connect($dsn, $username, $auth, {
Callbacks => {
prepare => sub {
$_[2] ||= {};
$_[2]->{pg_prepare_now} = 1;
return; # must return nothing
},
}
});
Note that we are editing the contents of @_ directly. In this case we've created the attributes hash if it's not passed to the prepare call.
@_ の内容を直接編集していることに注意してください。 この場合、これが prepare 呼び出しに渡されないなら属性ハッシュを 作成しています。
You can also prevent the associated method from ever executing. While a callback executes, $_ holds the method name. (This allows multiple callbacks to share the same code reference and still know what method was called.) To prevent the method from executing, simply undef $_. For example, if you wanted to disable calls to ping(), you could do this:
関連付けられたメソッドが実行されないようにすることもできます。 コールバックの実行中、$_はメソッド名を保持します。 (これにより、複数のコールバックが同じコード参照を共有し、どのメソッドが呼び出されたかを知ることができます。 )メソッドが実行されないようにするには、単純にundef $_を使用します。 たとえば、ping()の呼び出しを無効にする場合は、次のようにします: (TBR)
$dbh->{Callbacks} = {
ping => sub {
# tell dispatch to not call the method:
undef $_;
# return this value instead:
return "42 bells";
}
};
As with other attributes, Callbacks can be specified on a handle or via the attributes to connect(). Callbacks can also be applied to a statement methods on a statement handle. For example:
他の属性と同様に、コールバックはハンドル上で、またはconnect()の属性を介して指定できます。 コールバックは、文ハンドル上の文メソッドにも適用できます。 次に例を示します。 (TBR)
$sth->{Callbacks} = {
execute => sub {
print "Executing ", shift->{Statement}, "\n";
}
};
The Callbacks attribute of a database handle isn't copied to any statement handles it creates. So setting callbacks for a statement handle requires you to set the Callbacks attribute on the statement handle yourself, as in the example above, or use the special ChildCallbacks key described below.
データベースハンドルのCallbacks属性は、作成された文ハンドルにはコピーされません。 そのため、文ハンドルにコールバックを設定するには、前述の例のように文ハンドルにCallbacks属性を設定するか、次に説明する特殊なChildCallbacksキーを使用する必要があります。 (TBR)
Special Keys in Callbacks Attribute
Callbacks 属性の特殊キー
In addition to DBI handle method names, the Callbacks hash reference supports three additional keys.
DBI ハンドルメソッド名に加えて、Callbacks ハッシュリファレンスは 三つの追加のキーに対応しています。
The first is the ChildCallbacks key. When a statement handle is created from a database handle the ChildCallbacks key of the database handle's Callbacks attribute, if any, becomes the new Callbacks attribute of the statement handle. This allows you to define callbacks for all statement handles created from a database handle. For example, if you wanted to count how many times execute was called in your application, you could write:
1つ目はChildCallbacksキーです。 データベースハンドルから文ハンドルが作成されると、データベースハンドルのCallbacks属性のChildCallbacksキー(存在する場合)が、文ハンドルの新しいCallbacks属性になります。 これにより、データベースハンドルから作成されたすべての文ハンドルのコールバックを定義できます。 たとえば、アプリケーションでexecuteが呼び出された回数をカウントする場合は、次のように記述できます。 (TBR)
my $exec_count = 0;
my $dbh = DBI->connect( $dsn, $username, $auth, {
Callbacks => {
ChildCallbacks => {
execute => sub { $exec_count++; return; }
}
}
});
END {
print "The execute method was called $exec_count times\n";
}
The other two special keys are connect_cached.new and connect_cached.reused. These keys define callbacks that are called when connect_cached() is called, but allow different behaviors depending on whether a new handle is created or a handle is returned. The callback is invoked with these arguments: $dbh, $dsn, $user, $auth, $attr.
他の2つの特別なキーは、connect_cached.newおよびconnect_cached.reusedです。 これらのキーは、connect_cached()が呼び出されたときに呼び出されるコールバックを定義しますが、新しいハンドルが作成されるか、ハンドルが返されるかによって異なる動作が許可されます。 コールバックは、次の引数で呼び出されます:$dbh, $dsn, $user, $auth, $attr。 (TBR)
For example, some applications uses connect_cached() to connect with AutoCommit enabled and then disable AutoCommit temporarily for transactions. If connect_cached() is called during a transaction, perhaps in a utility method, then it might select the same cached handle and then force AutoCommit on, forcing a commit of the transaction. See the "connect_cached" documentation for one way to deal with that. Here we'll describe an alternative approach using a callback.
たとえば、一部のアプリケーションでは、connect_cached()を使用してAutoCommitを有効にして接続し、トランザクションに対して一時的にAutoCommitを無効にします。 トランザクション中にユーティリティメソッドなどでconnect_cached()が呼び出されると、キャッシュされた同じハンドルが選択され、AutoCommitが強制的にオンになり、トランザクションが強制的にコミットされる場合があります。 これに対処する1つの方法については、"connect_cached"の文書を参照してください。 ここでは、コールバックを使用する別のアプローチについて説明します。 (TBR)
Because the connect_cached.* callbacks are invoked before connect_cached() has applied the connect attributes you can use a callback to edit the attributes that will be applied. To prevent a cached handle from having its transactions committed before it's returned, you can eliminate the AutoCommit attribute in a connect_cached.reused callback, like so:
connect_cached.*コールバックは、connect_cached()が接続属性を適用する前に呼び出されるため、コールバックを使用して、適用される属性を編集できます。 キャッシュされたハンドルが戻される前にトランザクションがコミットされないようにするには、次のようにconnect_cached.reusedコールバックのAutoCommit属性を削除します。 (TBR)
my $cb = {
����connect_cached.reused���� => sub { delete $_[4]->{AutoCommit} },
};
sub dbh {
my $self = shift;
DBI->connect_cached( $dsn, $username, $auth, {
PrintError => 0,
RaiseError => 1,
AutoCommit => 1,
Callbacks => $cb,
});
}
The upshot is that new database handles are created with AutoCommit enabled, while cached database handles are left in whatever transaction state they happened to be in when retrieved from the cache.
その結果、新しいデータベースハンドルはAutoCommitを有効にして作成されますが、キャッシュされたデータベースハンドルは、キャッシュから取得されたときにたまたま存在していたトランザクション状態のままになります。 (TBR)
A more common application for callbacks is setting connection state only when a new connection is made (by connect() or connect_cached()). Adding a callback to the connected method makes this easy. This method is a no-op by default (unless you subclass the DBI and change it). The DBI calls it to indicate that a new connection has been made and the connection attributes have all been set. You can give it a bit of added functionality by applying a callback to it. For example, to make sure that MySQL understands your application's ANSI-compliant SQL, set it up like so:
コールバックのより一般的な用途は、(connect()またはconnect_cached()によって)新しい接続が作成されたときにのみ接続状態を設定することです。 接続されたメソッドにコールバックを追加すると、これが簡単になります。 このメソッドはデフォルトではno-opです(DBIをサブクラス化して変更しない限り)。 DBIはこのメソッドを呼び出して、新しい接続が作成され、接続属性がすべて設定されたことを示します。 コールバックを適用することで、少し機能を追加できます。 たとえば、MySQLがアプリケーションのANSI準拠のSQLを認識できるようにするには、次のように設定します: (TBR)
my $dbh = DBI->connect($dsn, $username, $auth, {
Callbacks => {
connected => sub {
shift->do(q{
SET SESSION sql_mode='ansi,strict_trans_tables,no_auto_value_on_zero';
});
return;
},
}
});
One significant limitation with callbacks is that there can only be one per method per handle. This means it's easy for one use of callbacks to interfere with, or typically simply overwrite, another use of callbacks. For this reason modules using callbacks should document the fact clearly so application authors can tell if use of callbacks by the module will clash with use of callbacks by the application.
コールバックの重要な制限の1つは、ハンドルごとにメソッドごとに1つしか存在できないことです。 これは、コールバックのある使用が、コールバックの別の使用と干渉したり、通常は単に上書きしたりすることが容易であることを意味します。 このため、コールバックを使用するモジュールは、モジュールによるコールバックの使用がアプリケーションによるコールバックの使用と競合するかどうかをアプリケーション作成者が判断できるように、その事実を明確に文書化する必要があります。 (TBR)
You might be able to work around this issue by taking a copy of the original callback and calling it within your own. For example:
元のコールバックのコピーを取って、そちらを呼ぶことでこの問題を 回避できるかもしれません。 例えば:
my $prev_cb = $h->{Callbacks}{method_name};
$h->{Callbacks}{method_name} = sub {
if ($prev_cb) {
my @result = $prev_cb->(@_);
return @result if not $_; # $prev_cb vetoed call
}
... your callback logic here ...
};
private_your_module_name_*¶
The DBI provides a way to store extra information in a DBI handle as "private" attributes. The DBI will allow you to store and retrieve any attribute which has a name starting with "private_".
DBI は「プライベート」属性として、DBI ハンドルでの特別な情報を格納する 方法を提供しています。 DBI では "private_" で始まる名前の属性を格納、参照することができます。
It is strongly recommended that you use just one private attribute (e.g., use a hash ref) and give it a long and unambiguous name that includes the module or application name that the attribute relates to (e.g., "private_YourFullModuleName_thingy").
ただしプライベート属性は(例えばハッシュのリファレンスを使うなどにより) 一つ だけとし、かつ その属性に関連するモジュールまたは アプリケーション名が入った長くて他にはないような名前にすることを 強く お勧めします(例えば "private_YourFullModuleName_thingy")。
Because of the way the Perl tie mechanism works you cannot reliably use the ||= operator directly to initialise the attribute, like this:
Perl の tie 機構の動作手法により、以下のように、属性を初期化するために 信頼できる形で||= 演算子を直接使うことはできません。
my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG
you should use a two step approach like this:
以下のように二段階の手法を使うべきです:
my $foo = $dbh->{private_yourmodname_foo};
$foo ||= $dbh->{private_yourmodname_foo} = { ... };
This attribute is primarily of interest to people sub-classing DBI, or for applications to piggy-back extra information onto DBI handles.
この属性は基本的に DBI をサブクラス化する人々や、DBI ハンドルに その他の情報を追加するアプリケーションが関心を持つものです。
DBI データベースハンドルオブジェクト¶
This section covers the methods and attributes associated with database handles.
このセクションはデータベース・ハンドルに関連するメソッドと属性について カバーします。
データベースハンドルメソッド¶
The following methods are specified for DBI database handles:
以下のメソッドがDBIデータベース・ハンドルに指定されています:
clone¶
$new_dbh = $dbh->clone();
$new_dbh = $dbh->clone(\%attr);
The clone method duplicates the $dbh connection by connecting with the same parameters ($dsn, $user, $password) as originally used.
clone メソッドは、$dbh 接続を、同じパラメータ ($dsn, $user, $password) で 接続することで複製します。
The attributes for the cloned connect are the same as those used for the original connect, with some other attributes merged over them depending on the \%attr parameter.
複製された接続の属性は元の接続のものと同じものに、\%attr 引数によるものが マージされたものです。
If \%attr is given then the attributes it contains are merged into the original attributes and override any with the same names. Effectively the same as doing:
\%attrが指定された場合、それに含まれる属性は元の属性にマージされ、同じ名前の属性は上書きされます。 次の操作と実質的に同じです。 (TBR)
%attribues_used = ( %original_attributes, %attr );
If \%attr is not given then it defaults to a hash containing all the attributes in the attribute cache of $dbh excluding any non-code references, plus the main boolean attributes (RaiseError, PrintError, AutoCommit, etc.). This behaviour is subject to change.
\%attrを指定しない場合、デフォルトでは、$dbhの属性キャッシュ内のすべての属性(コード参照以外を除く)に加えて、主要なブール属性(RaiseError、PrintError、AutoCommitなど)を含むハッシュが使用されます。 この動作は変更されることがあります。 (TBR)
The clone method can be used even if the database handle is disconnected.
clone メソッドは例えばデータベースハンドルの接続が切れていても使えます。
The clone method was added in DBI 1.33. It is very new and likely to change.
clone メソッドは DBI 1.33 で追加されました。 これはとても新しく、変更されるかもしれません。
data_sources¶
@ary = $dbh->data_sources();
@ary = $dbh->data_sources(\%attr);
Returns a list of data sources (databases) available via the $dbh driver's data_sources() method, plus any extra data sources that the driver can discover via the connected $dbh. Typically the extra data sources are other databases managed by the same server process that the $dbh is connected to.
$dbhドライバのdata_sources()メソッドで使用可能なデータソース(データベース)のリストと、接続された$dbhを介してドライバが検出できる追加のデータソースを返します。 通常、追加のデータソースは、$dbhが接続されているのと同じサーバプロセスによって管理されている他のデータベースです。 (TBR)
Data sources are returned in a form suitable for passing to the "connect" method (that is, they will include the "dbi:$driver:" prefix).
データソースは "connect" メソッドに渡すのに適したな形式で返されます (つまり接頭辞 "dbi:$driver:" が入ります。)
The data_sources() method, for a $dbh, was added in DBI 1.38.
$dbh のための data_sources() メソッドは DBI 1.38 で追加されました。
do¶
$rows = $dbh->do($statement) or die $dbh->errstr;
$rows = $dbh->do($statement, \%attr) or die $dbh->errstr;
$rows = $dbh->do($statement, \%attr, @bind_values) or die ...
Prepare and execute a single statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available.
一つの文を prepare し、execute します。 影響を受けた行の数を、またエラーであれば undef を返します。 -1 は行の数が分からないか使用できないことを意味します。
This method is typically most useful for non-SELECT statements that either cannot be prepared in advance (due to a limitation of the driver) or do not need to be executed repeatedly. It should not be used for SELECT statements because it does not return a statement handle (so you can't fetch any data).
このメソッドは典型的には、(ドライバの制限により)前もって prepare されることが なかったり、繰り返し実行しない SELECT 以外 の文でとても有効です。 文ハンドルを返さない(そのために何もデータを取り出せない)ので、 SELECT 文では使うべきではありません。
The default do method is logically similar to:
デフォルトのdoメソッドは、論理的には以下のものと同様です:
sub do {
my($dbh, $statement, $attr, @bind_values) = @_;
my $sth = $dbh->prepare($statement, $attr) or return undef;
$sth->execute(@bind_values) or return undef;
my $rows = $sth->rows;
($rows == 0) ? "0E0" : $rows; # always return true if no error
}
For example:
例えば:
my $rows_deleted = $dbh->do(q{
DELETE FROM table
WHERE status = ?
}, undef, 'DONE') or die $dbh->errstr;
Using placeholders and @bind_values with the do method can be useful because it avoids the need to correctly quote any variables in the $statement. But if you'll be executing the statement many times then it's more efficient to prepare it once and call execute many times instead.
プレースホルダとバインド変数(@bind_values) を do メソッドで使うと、 $statement の中の変数を正しくクォートしなくてもよくなるためにとても 便利です。 しかしもし文を何度も実行するのであれば、代わりに 一度 prepare し、何度も execute するほうがより効率的です。
The q{...} style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote-like qq{...} operator if you want to interpolate variables into the string. See "Quote and Quote-like Operators" in perlop for more details.
この例で使われている q{ ...} 形式のクォートは、文で 使われているかもしれないクォートの対応を壊されないように使われています。 文字列に入っている変数を解釈したい場合には、ダブルクォート風 qq{...} 演算子を使います。 詳細は "Quote and Quote-like Operators" in perlop をご覧ください。
last_insert_id¶
$rv = $dbh->last_insert_id($catalog, $schema, $table, $field);
$rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
Returns a value 'identifying' the row just inserted, if possible. Typically this would be a value assigned by the database server to a column with an auto_increment or serial type. Returns undef if the driver does not support the method or can't determine the value.
可能であれば、挿入された行を'識別する'値を返します。 通常、これはauto_incrementまたはserialタイプの列にデータベースサーバによって割り当てられた値です。 ドライバがメソッドをサポートしていない場合、または値を判別できない場合は、undefを返します。 (TBR)
The $catalog, $schema, $table, and $field parameters may be required for some drivers (see below). If you don't know the parameter values and your driver does not need them, then use undef for each.
一部のドライバでは、$catalog、$schema、$table、および$fieldパラメータが必要になる場合があります(以下を参照)。 パラメータの値がわからず、ドライバがそれらを必要としない場合は、それぞれにundefを使用します。 (TBR)
There are several caveats to be aware of with this method if you want to use it for portable applications:
このメソッドを移植性のあるアプリケーションに使いたいなら、注意するべき いくつかの警告があります:
* For some drivers the value may only available immediately after the insert statement has executed (e.g., mysql, Informix).
* ドライバによっては(mysql, Informix など)、値が insert 文が実行された 直後でのみ利用可能である場合があります。
* For some drivers the $catalog, $schema, $table, and $field parameters are required, for others they are ignored (e.g., mysql).
* ドライバによっては (mysql など)、$catalog, $schema, $table, $field パラメータが必要であったり、無視されたりします。
* Drivers may return an indeterminate value if no insert has been performed yet.
* insert 文がまだ実行されていない場合、ドライバは不定な値を 返すかもしれません。
* For some drivers the value may only be available if placeholders have not been used (e.g., Sybase, MS SQL). In this case the value returned would be from the last non-placeholder insert statement.
*一部のドライバ(Sybase、MS SQLなど)では、プレースホルダnotが使用されている場合にのみ値が使用可能です。 この場合、返される値は、最後の非プレースホルダ挿入ステートメントからの値になります。 (TBR)
* Some drivers may need driver-specific hints about how to get the value. For example, being told the name of the database 'sequence' object that holds the value. Any such hints are passed as driver-specific attributes in the \%attr parameter.
*ドライバによっては、値の取得方法に関するドライバ固有のヒントが必要な場合があります。 たとえば、値を保持するデータベースのsequenceオブジェクトの名前が通知されます。 このようなヒントは、\%attrパラメータにドライバ固有の属性として渡されます。 (TBR)
* If the underlying database offers nothing better, then some drivers may attempt to implement this method by executing "select max($field) from $table". Drivers using any approach like this should issue a warning if AutoCommit is true because it is generally unsafe - another process may have modified the table between your insert and the select. For situations where you know it is safe, such as when you have locked the table, you can silence the warning by passing Warn => 0 in \%attr.
*基盤となるデータベースがこれよりも優れたものを提供しない場合、一部のドライバは"select max($field) from $table"を実行してこのメソッドを実装しようとする可能性があります。 このようなアプローチを使用するドライバは、AutoCommitがtrueの場合に警告を発行する必要があります。 これは、一般的に安全ではないためです。 別のプロセスが挿入と選択の間にテーブルを変更した可能性があります。 テーブルをロックした場合など、安全であることがわかっている状況では、\%attrにWarn=>0を渡すことによって警告を抑止できます。 (TBR)
* If no insert has been performed yet, or the last insert failed, then the value is implementation defined.
* まだ insert 文が実行されていなかったり、最後の insert 文が 失敗していたりした場合、値は実装依存です。
Given all the caveats above, it's clear that this method must be used with care.
上述全ての注意点から、このメソッドは注意して使わなければならないことは 明らかです。
The last_insert_id method was added in DBI 1.38.
last_insert_id メソッドは DBI 1.38 で追加されました。
selectrow_array¶
@row_ary = $dbh->selectrow_array($statement);
@row_ary = $dbh->selectrow_array($statement, \%attr);
@row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute" and "fetchrow_array" into a single call. If called in a list context, it returns the first row of data from the statement. The $statement parameter can be a previously prepared statement handle, in which case the prepare is skipped.
このユーティリティーメソッドは、"prepare", "execute", "fetchrow_array" を一回にまとめておこないます。 リストコンテキストで呼ばれれば、その文によって返される 最初の行を返します。 $statement パラメータはすでに prepare されている 文ハンドルにすることができます。 その場合、prepare は飛ばされます。
If any method fails, and "RaiseError" is not set, selectrow_array will return an empty list.
いずれかのメソッドがエラーとなり、"RaiseError" が設定されていなければ、 selectrow_array は空のリストを返します。
If called in a scalar context for a statement handle that has more than one column, it is undefined whether the driver will return the value of the first column or the last. So don't do that. Also, in a scalar context, an undef is returned if there are no more rows or if an error occurred. That undef can't be distinguished from an undef returned because the first field value was NULL. For these reasons you should exercise some caution if you use selectrow_array in a scalar context, or just don't do that.
複数列のある文ハンドルに対してスカラコンテキストで呼び出すと、 ドライバが最初の列を返すか最後の列を返すかは未定義です。 従って、やってはいけません。 また、スカラコンテキストでは、 もう行がないかエラーが発生したならば、undef が返されます。 この undef は最初にフィールドの値が NULL であったために返された undef と区別することができません。 これらの理由によって、selectrow_array をスカラコンテキストで 呼び出すときには注意するか、単に使わないようにしてください。
selectrow_arrayref¶
$ary_ref = $dbh->selectrow_arrayref($statement);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute" and "fetchrow_arrayref" into a single call. It returns the first row of data from the statement. The $statement parameter can be a previously prepared statement handle, in which case the prepare is skipped.
このユーティリティメソッドは、"prepare"、"execute"、および"fetchrow_arrayref"を1回の呼び出しに結合します。 ステートメントからデータの最初の行を返します。 $statementパラメータには、以前に準備されたステートメントハンドルを指定できます。 この場合、prepareはスキップされます。 (TBR)
If any method fails, and "RaiseError" is not set, selectrow_array will return undef.
いずれかのメソッドが失敗して、"RaiseError" がセットされていない場合は、 selectrow_array は undef を返します。
selectrow_hashref¶
$hash_ref = $dbh->selectrow_hashref($statement);
$hash_ref = $dbh->selectrow_hashref($statement, \%attr);
$hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute" and "fetchrow_hashref" into a single call. It returns the first row of data from the statement. The $statement parameter can be a previously prepared statement handle, in which case the prepare is skipped.
このユーティリティメソッドは、"prepare"、"execute"、および"fetchrow_hashref"を1回の呼び出しに結合します。 ステートメントからデータの最初の行を返します。 $statementパラメータには、以前に準備されたステートメントハンドルを指定できます。 この場合、prepareはスキップされます。 (TBR)
If any method fails, and "RaiseError" is not set, selectrow_hashref will return undef.
いずれかのメソッドが失敗して、"RaiseError" がセットされていない場合は、 selectrow_hashref は undef を返します。
selectall_arrayref¶
$ary_ref = $dbh->selectall_arrayref($statement);
$ary_ref = $dbh->selectall_arrayref($statement, \%attr);
$ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute" and "fetchall_arrayref" into a single call. It returns a reference to an array containing a reference to an array (or hash, see below) for each row of data fetched.
このユーティリティメソッドは、"prepare", "execute", "fetchall_arrayref" を一回にまとめておこないます。 取り出されたデータの各行の配列(またはハッシュ; 後述)へのリファレンスが入った 配列へのリファレンスを返します。
The $statement parameter can be a previously prepared statement handle, in which case the prepare is skipped. This is recommended if the statement is going to be executed many times.
$statement パラメータを既に prepare されている文ハンドルに することができます; その場合、prepare は飛ばされます。 これは何回も文が実行する予定であればお勧めです。
If "RaiseError" is not set and any method except fetchall_arrayref fails then selectall_arrayref will return undef; if fetchall_arrayref fails then it will return with whatever data has been fetched thus far. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the data is complete or was truncated due to an error.
"RaiseError"が設定されておらず、fetchall_arrayref以外のメソッドが失敗した場合、selectall_arrayrefはundefを返します。 fetchall_arrayrefが失敗した場合は、これまでにフェッチされたデータを返します。 後で$sth->errをチェックして(またはRaiseError属性を使用して)、データが完全であるか、エラーのために切り捨てられたかを検出する必要があります。 (TBR)
The "fetchall_arrayref" method called by selectall_arrayref supports a $max_rows parameter. You can specify a value for $max_rows by including a 'MaxRows' attribute in \%attr. In which case finish() is called for you after fetchall_arrayref() returns.
selectall_arrayrefによって呼び出される"fetchall_arrayref"メソッドは、$max_rowsパラメータをサポートしています。 \%attrに'MaxRows'属性を含めることによって、$max_rowsの値を指定できます。 この場合、fetchall_arrayref()が返された後にfinish()が呼び出されます。 (TBR)
The "fetchall_arrayref" method called by selectall_arrayref also supports a $slice parameter. You can specify a value for $slice by including a 'Slice' or 'Columns' attribute in \%attr. The only difference between the two is that if Slice is not defined and Columns is an array ref, then the array is assumed to contain column index values (which count from 1), rather than perl array index values. In which case the array is copied and each value decremented before passing to /fetchall_arrayref.
selectall_arrayrefによって呼び出される"fetchall_arrayref"メソッドも、$sliceパラメータをサポートします。 \%attrに'Slice'または'Columns'属性を含めることによって、$sliceの値を指定できます。 この2つの唯一の違いは、Sliceが定義されておらず、Columnsが配列参照である場合、配列にはperl配列インデックス値ではなく、(1からカウントされる)列インデックス値が含まれていると見なされることです。 この場合、配列はコピーされ、各値は/fetchall_arrayrefに渡される前にデクリメントされます。 (TBR)
You may often want to fetch an array of rows where each row is stored as a hash. That can be done simple using:
各行をハッシュとして保管している行の配列をフェッチしたいことが多いでしょう。 単純に以下のようにしてできます:
my $emps = $dbh->selectall_arrayref(
"SELECT ename FROM emp ORDER BY ename",
{ Slice => {} }
);
foreach my $emp ( @$emps ) {
print "Employee: $emp->{ename}\n";
}
Or, to fetch into an array instead of an array ref:
または、フェッチ内容を配列リファレンスではなく配列に入れるには:
@result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) };
See "fetchall_arrayref" method for more details.
更なる詳細については "fetchall_arrayref" メソッドを参照してください。
selectall_hashref¶
$hash_ref = $dbh->selectall_hashref($statement, $key_field);
$hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr);
$hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values);
This utility method combines "prepare", "execute" and "fetchall_hashref" into a single call. It returns a reference to a hash containing one entry, at most, for each row, as returned by fetchall_hashref().
このユーティリティメソッドは、"prepare"、"execute"、および"fetchall_hashref"を1回の呼び出しに結合します。 fetchall_hashref()によって返されるように、各行に対して最大1つのエントリを含むハッシュへの参照を返します。 (TBR)
The $statement parameter can be a previously prepared statement handle, in which case the prepare is skipped. This is recommended if the statement is going to be executed many times.
$statement パラメータを既に prepare されている文ハンドルに することができます; その場合、prepare は飛ばされます。 これは何回も文が実行する予定であればお勧めです。
The $key_field parameter defines which column, or columns, are used as keys in the returned hash. It can either be the name of a single field, or a reference to an array containing multiple field names. Using multiple names yields a tree of nested hashes.
$key_fieldパラメータは、返されるハッシュでキーとして使用される列を定義します。 単一のフィールドの名前、または複数のフィールド名を含む配列への参照を指定できます。 複数の名前を使用すると、ネストされたハッシュのツリーが生成されます。 (TBR)
If a row has the same key as an earlier row then it replaces the earlier row.
行が以前の行と同じキーの場合、以前の行は置き換えられます。
If any method except fetchrow_hashref fails, and "RaiseError" is not set, selectall_hashref will return undef. If fetchrow_hashref fails and "RaiseError" is not set, then it will return with whatever data it has fetched thus far. $DBI::err should be checked to catch that.
fetchrow_hashref 以外のいずれかのメソッドがエラーとなり、 "RaiseError" が設定されていなければ、selectall_hashref は undefを返します。 もし fetchrow_hashref が失敗し、"RaiseError" が設定されていなければ、 それまでに取り出したデータをなるべく多く返します。 それを捕らえるために $DBI::err をチェックすべきです。
See fetchall_hashref() for more details.
さらなる詳細については fetchall_hashref() を参照してください。
selectcol_arrayref¶
$ary_ref = $dbh->selectcol_arrayref($statement);
$ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
$ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute", and fetching one column from all the rows, into a single call. It returns a reference to an array containing the values of the first column from each row.
このユーティリティーメソッドは、一回に "prepare", "execute" を まとめておこない、すべての行から一つのカラムからを取り出します。 各行からの最初のカラムの値が入った配列へのリファレンスを返します。
The $statement parameter can be a previously prepared statement handle, in which case the prepare is skipped. This is recommended if the statement is going to be executed many times.
$statement パラメータを既に prepare されている文ハンドルに することができます; その場合、prepare は飛ばされます。 これは何回も文が実行する予定であればお勧めです。
If any method except fetch fails, and "RaiseError" is not set, selectcol_arrayref will return undef. If fetch fails and "RaiseError" is not set, then it will return with whatever data it has fetched thus far. $DBI::err should be checked to catch that.
fetch 以外のいずれかのメソッドがエラーとなり、"RaiseError" が 設定されていなければ、selectcol_arrayref は undef を返します。 もし fetch が失敗し、/RaiseError が設定されていなければ、それまでに 取り出したデータをなるべく多く返します。 それを捕らえるために $DBI::err をチェックすべきです。
The selectcol_arrayref method defaults to pushing a single column value (the first) from each row into the result array. However, it can also push another column, or even multiple columns per row, into the result array. This behaviour can be specified via a 'Columns' attribute which must be a ref to an array containing the column number or numbers to use. For example:
selectcol_arrayrefメソッドのデフォルトでは、各行の単一の列値(最初)が結果配列にプッシュされます。 ただし、別の列、または行ごとに複数の列を結果配列にプッシュすることもできます。 この動作は、'Columns'属性を介して指定できます。 この属性は、使用する列番号を含む配列への参照である必要があります。 次に例を示します。 (TBR)
# get array of id and name pairs:
my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] });
my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name
You can specify a maximum number of rows to fetch by including a 'MaxRows' attribute in \%attr.
最大フェッチ行数は \%attr の 'MaxRows' 属性で指定できます。
prepare¶
$sth = $dbh->prepare($statement) or die $dbh->errstr;
$sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr;
Prepares a statement for later execution by the database engine and returns a reference to a statement handle object.
一つの文を後でデータベースエンジンによって実行できるように準備し、 文ハンドルオブジェクトへのリファレンスを返します。
The returned statement handle can be used to get attributes of the statement and invoke the "execute" method. See "Statement Handle Methods".
返される文ハンドルは文の属性を取得したり、 "execute" メソッドの呼び出しに使われます。 "Statement Handle Methods" をご覧ください。
Drivers for engines without the concept of preparing a statement will typically just store the statement in the returned handle and process it when $sth->execute is called. Such drivers are unlikely to give much useful information about the statement, such as $sth->{NUM_OF_FIELDS}, until after $sth->execute has been called. Portable applications should take this into account.
準備された文という考えが無いドライバでは、通常、返される ハンドルに文を保存し、$sth->execute が呼ばれたらそれを 処理します。 そのようなドライバは $sth->{NUM_OF_FIELDS} のような 文について有効な情報を $sth->execute が呼ばれるまでは、 取得できることはまずありません。 移植可能なアプリケーションはこの点を注意する必要があります。
In general, DBI drivers do not parse the contents of the statement (other than simply counting any "Placeholders"). The statement is passed directly to the database engine, sometimes known as pass-thru mode. This has advantages and disadvantages. On the plus side, you can access all the functionality of the engine being used. On the downside, you're limited if you're using a simple engine, and you need to take extra care if writing applications intended to be portable between engines.
通常、DBIドライバは文を解析しません (そうでなければ単純にプレースホルダを数えます)。 文はデータベース・エンジンに直接渡されます、いわゆるパススルー モードです。 これは長所でも短所でもあります。 よく言えば、使われているエンジンのすべての機能にアクセスすることができます。 悪く言えば、簡単なエンジンを使っていれば制限されますし、エンジンをまたがって 移植可能なアプリケーションを書こうとすれば、非常に注意する必要があります。
Portable applications should not assume that a new statement can be prepared and/or executed while still fetching results from a previous statement.
移植可能なアプリケーションは、まだ前の文から結果を 取り出している間に、新しい文が prepare でき、そして/あるいは 実行できると想定するべきではありません。
Some command-line SQL tools use statement terminators, like a semicolon, to indicate the end of a statement. Such terminators should not normally be used with the DBI.
いくつかのコマンドライン型 SQL ツールは、セミコロンなどのステータスの終わりを 示すために、文末尾文字(statement terminator)を使っています。 通常そうした末尾文字を DBI で使われません。
prepare_cached¶
$sth = $dbh->prepare_cached($statement)
$sth = $dbh->prepare_cached($statement, \%attr)
$sth = $dbh->prepare_cached($statement, \%attr, $if_active)
Like "prepare" except that the statement handle returned will be stored in a hash associated with the $dbh. If another call is made to prepare_cached with the same $statement and %attr parameter values, then the corresponding cached $sth will be returned without contacting the database server.
$dbh に関連付けられたハッシュに保存されることを除いて "prepare" と 同様です。 もし同じ $statement と %attr パラメータの値ででもう一度 prepare_cached が呼び出されると、データベースサーバに コンタクトすることなく、対応する $sth が返されます。
The $if_active parameter lets you adjust the behaviour if an already cached statement handle is still Active. There are several alternatives:
$if_activeパラメータを使用すると、すでにキャッシュされているステートメントハンドルがまだアクティブである場合の動作を調整できます。 いくつかの選択肢があります。 (TBR)
- 0: A warning will be generated, and finish() will be called on the statement handle before it is returned. This is the default behaviour if $if_active is not passed.
- 1: finish() will be called on the statement handle, but the warning is suppressed.
- 2: Disables any checking.
- 3: The existing active statement handle will be removed from the cache and a new statement handle prepared and cached in its place. This is the safest option because it doesn't affect the state of the old handle, it just removes it from the cache. [Added in DBI 1.40]
Here are some examples of prepare_cached:
以下は prepare_cached の例です:
sub insert_hash {
my ($table, $field_values) = @_;
# sort to keep field order, and thus sql, stable for prepare_cached
my @fields = sort keys %$field_values;
my @values = @{$field_values}{@fields};
my $sql = sprintf "insert into %s (%s) values (%s)",
$table, join(",", @fields), join(",", ("?")x@fields);
my $sth = $dbh->prepare_cached($sql);
return $sth->execute(@values);
}
sub search_hash {
my ($table, $field_values) = @_;
# sort to keep field order, and thus sql, stable for prepare_cached
my @fields = sort keys %$field_values;
my @values = @{$field_values}{@fields};
my $qualifier = "";
$qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields;
$sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier");
return $dbh->selectall_arrayref($sth, {}, @values);
}
Caveat emptor: This caching can be useful in some applications, but it can also cause problems and should be used with care. Here is a contrived case where caching would cause a significant problem:
Caveat emptor:このキャッシュは、一部のアプリケーションでは便利ですが、問題を引き起こす可能性があるため、注意して使用する必要があります。 キャッシュが重大な問題を引き起こす場合を考えてみましょう。 (TBR)
my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
$sth->execute(...);
while (my $data = $sth->fetchrow_hashref) {
# later, in some other code called within the loop...
my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
$sth2->execute(...);
while (my $data2 = $sth2->fetchrow_arrayref) {
do_stuff(...);
}
}
In this example, since both handles are preparing the exact same statement, $sth2 will not be its own statement handle, but a duplicate of $sth returned from the cache. The results will certainly not be what you expect. Typically the inner fetch loop will work normally, fetching all the records and terminating when there are no more, but now that $sth is the same as $sth2 the outer fetch loop will also terminate.
この例では、両方のハンドルがまったく同じステートメントを準備しているため、$sth2はそれ自体のステートメントハンドルではなく、キャッシュから返された$sthの複製になります。 結果は期待したものではありません。 通常、内側のフェッチループは正常に動作し、すべてのレコードをフェッチし、それ以上レコードがないときに終了しますが、$sthが$sth2と同じになったので、外側のフェッチループも終了します。 (TBR)
You'll know if you run into this problem because prepare_cached() will generate a warning by default (when $if_active is false).
prepare_cached()はデフォルトで($if_activeがfalseの場合)警告を生成するので、この問題が発生した場合はすぐにわかります。 (TBR)
The cache used by prepare_cached() is keyed by both the statement and any attributes so you can also avoid this issue by doing something like:
prepare_cached()で使用されるキャッシュは、文と属性の両方によってキー設定されるため、次のようにしてこの問題を回避することもできます。 (TBR)
$sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ });
which will ensure that prepare_cached only returns statements cached by that line of code in that source file.
これにより、prepare_cachedは、そのソースファイル内のそのコード行によってキャッシュされたステートメントのみを返すようになります。 (TBR)
If you'd like the cache to managed intelligently, you can tie the hashref returned by CachedKids to an appropriate caching module, such as Tie::Cache::LRU:
キャッシュをインテリジェントに管理したい場合は、CachedKidsによって返されるhashrefを、Tie::Cache::LRUのような適切なキャッシュモジュールに結び付けることができます。 (TBR)
my $cache;
tie %$cache, 'Tie::Cache::LRU', 500;
$dbh->{CachedKids} = $cache;
commit¶
$rc = $dbh->commit or die $dbh->errstr;
Commit (make permanent) the most recent series of database changes if the database supports transactions and AutoCommit is off.
データベースがトランザクションをサポートしていて AutoCommit がオフであれば、 データベースに対する直近の一連の変更をコミット(永続化)します。
If AutoCommit is on, then calling commit will issue a "commit ineffective with AutoCommit" warning.
AutoCommit がオンであれば、commit は "commit ineffective with AutoCommit" という警告を起こします。
See also "Transactions" in the "FURTHER INFORMATION" section below.
後述する "FURTHER INFORMATION" 章の "Transactions" も参照してください。
rollback¶
$rc = $dbh->rollback or die $dbh->errstr;
Rollback (undo) the most recent series of uncommitted database changes if the database supports transactions and AutoCommit is off.
データベースがトランザクションをサポートしていて、AutoCommit がオフであれば、 データベースに対する直近の一連の変更をロールバックします(元に戻します)。
If AutoCommit is on, then calling rollback will issue a "rollback ineffective with AutoCommit" warning.
AutoCommit がオンであれば、rollback は "rollback ineffective with AutoCommit" という警告を起こします。
See also "Transactions" in the "FURTHER INFORMATION" section below.
後述する "FURTHER INFORMATION" 章の "Transactions" も参照してください。
begin_work¶
$rc = $dbh->begin_work or die $dbh->errstr;
Enable transactions (by turning AutoCommit off) until the next call to commit or rollback. After the next commit or rollback, AutoCommit will automatically be turned on again.
次にcommitまたはrollbackを呼び出すまで、(AutoCommitをオフにして)トランザクションを有効にします。 次のcommitまたはrollbackの後、AutoCommitは自動的に再びオンになります。 (TBR)
If AutoCommit is already off when begin_work is called then it does nothing except return an error. If the driver does not support transactions then when begin_work attempts to set AutoCommit off the driver will trigger a fatal error.
begin_workが呼び出されたときにAutoCommitがすでにオフになっている場合は、エラーを返す以外は何もしません。 ドライバがトランザクションをサポートしていない場合、begin_workがAutoCommitをオフに設定しようとすると、ドライバは致命的なエラーをトリガします。 (TBR)
See also "Transactions" in the "FURTHER INFORMATION" section below.
後述する "FURTHER INFORMATION" 章の "Transactions" も参照してください。
disconnect¶
$rc = $dbh->disconnect or warn $dbh->errstr;
Disconnects the database from the database handle. disconnect is typically only used before exiting the program. The handle is of little use after disconnecting.
データベースハンドルをデータベースから切断します。 disconnect は普通プログラムを終了するときにだけ使います。 切断した後、ハンドルほとんど役に立ちません。
The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect.
残念ながら disconnect メソッドにより、トランザクションがどうなるかは 決まっていません。 ある種のデータベースシステム(Oracle、Ingressなど)は自動的に変更を コミットしますが、(Infromixなど)変更をロールバックするものもあります。 AutoCommit を使わないアプリケーションは disconnect を呼び出す前に、 明確に commit または rollback を呼び出すべきです。
The database is automatically disconnected by the DESTROY method if still connected when there are no longer any references to the handle. The DESTROY method for each driver should implicitly call rollback to undo any uncommitted changes. This is vital behaviour to ensure that incomplete transactions don't get committed simply because Perl calls DESTROY on every object before exiting. Also, do not rely on the order of object destruction during "global destruction", as it is undefined.
まだ接続していて、ハンドルへの参照がまったくなくなった場合、 DESTROY メソッドによりデータベースは自動的に切断されます。 各ドライバへの DESTROY メソッドはコミットされていない変更を元に戻すため、 暗黙のうちに rollback を呼び出します。 これは終了する前に Perl が単に各オブジェクトに DESTROY を 呼び出すことによって、不完全なトランザクションがコミットされないということを 保証するためにきわめて重要です。 同様に「グローバルな破壊」でのオブジェクトの破壊の順序は信頼できません; これは未定義です。
Generally, if you want your changes to be committed or rolled back when you disconnect, then you should explicitly call "commit" or "rollback" before disconnecting.
一般的に、切断する前に変更をコミットまたはロールバックしたいのであれば、 切断する前に明示的に "commit" または "rollback" を呼び出すべきです。
If you disconnect from a database while you still have active statement handles (e.g., SELECT statement handles that may have more data to fetch), you will get a warning. The warning may indicate that a fetch loop terminated early, perhaps due to an uncaught error. To avoid the warning call the finish method on the active handles.
Active な文ハンドル(つまり、まだフェッチするデータがある SELECT 文 ハンドル)があるのにデータベースから切断すると警告を受けます。 警告はフェッチループが早く終わってしまったことを示していて、おそらくは 捕捉していないエラーによるものです。 警告を避けるには、アクティブハンドルに対して finish メソッドを 呼び出します。
ping¶
$rc = $dbh->ping;
Attempts to determine, in a reasonably efficient way, if the database server is still running and the connection to it is still working. Individual drivers should implement this function in the most suitable manner for their database engine.
合理的で効率的な方法で、データベースサーバーが稼動しているか、接続が 動いているかを判定しようとします。各ドライバはこの関数をそれぞれの データベースに最も適切な方法で実装するべきです。
The current default implementation always returns true without actually doing anything. Actually, it returns "0 but true" which is true but zero. That way you can tell if the return value is genuine or just the default. Drivers should override this method with one that does the right thing for their type of database.
現在の デフォルトの 実装は、実際には何もせず常に真を返します。 実際には、それは「0 だが真」を返します; これは真ですが 0 です。 これにより返された値が本物なのか単なるデフォルトなのかがわかります。 ドライバはこのメソッドをデータベースのタイプにあったものでこのメソッドを 上書きしなければなりません。
Few applications would have direct use for this method. See the specialized Apache::DBI module for one example usage.
アプリケーションでこのメソッドを使うことはあまりないでしょう。 使用例としては専門的な Apache::DBI モジュールをご覧ください。
get_info¶
$value = $dbh->get_info( $info_type );
Returns information about the implementation, i.e. driver and data source capabilities, restrictions etc. It returns undef for unknown or unimplemented information types. For example:
実装に関する情報(ドライバおよびデータソースの機能、制限など)を戻します。 不明または実装されていない情報タイプの場合は、undefを戻します。 次に例を示します。 (TBR)
$database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER
$max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT
See "Standards Reference Information" for more detailed information about the information types and their meanings and possible return values.
情報型とその意味およびあり得る返り値に関するさらに詳しい情報については "Standards Reference Information" を参照してください。
The DBI::Const::GetInfoType module exports a %GetInfoType hash that can be used to map info type names to numbers. For example:
DBI::Const::GetInfoType モジュールは、型名を数値にマッピングするために 使える %GetInfoType ハッシュをエクスポートします。 例えば:
$database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );
The names are a merging of the ANSI and ODBC standards (which differ in some cases). See DBI::Const::GetInfoType for more details.
名前は ANSI と ODBC の標準 (一部で異なります) をマージしたものです。 さらなる詳細については DBI::Const::GetInfoType を参照してください。
Because some DBI methods make use of get_info(), drivers are strongly encouraged to support at least the following very minimal set of information types to ensure the DBI itself works properly:
DBIメソッドの中にはget_info()を利用するものがあるので、DBI自体が正しく動作するように、ドライバは<少なくとも>以下の最小限の情報タイプをサポートすることを強く推奨します。 (TBR)
Type Name Example A Example B
---- -------------------------- ------------ ----------------
17 SQL_DBMS_NAME 'ACCESS' 'Oracle'
18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...'
29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"'
41 SQL_CATALOG_NAME_SEPARATOR '.' '@'
114 SQL_CATALOG_LOCATION 1 2
table_info¶
$sth = $dbh->table_info( $catalog, $schema, $table, $type );
$sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr );
# then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
Returns an active statement handle that can be used to fetch information about tables and views that exist in the database.
データベースに存在するテーブルやビューの情報を取得するために使われる Active な文・ハンドルを返します。
The arguments $catalog, $schema and $table may accept search patterns according to the database/driver, for example: $table = '%FOO%'; Remember that the underscore character ('_') is a search pattern that means match any character, so 'FOO_%' is the same as 'FOO%' and 'FOO_BAR%' will match names like 'FOO1BAR'.
引数 $catalog, $schema, $table はデータベース/ドライバによって検索 パターンを受け取るかもしれません。 例えば: $table = '%FOO%'; 下線文字 ('_') は任意の文字を意味する検索パターンを意味するので、 'FOO_%' は 'FOO%' と同じで、'FOO_BAR%' は 'FOO1BAR' のような名前に マッチングするということに注意してください。
The value of $type is a comma-separated list of one or more types of tables to be returned in the result set. Each value may optionally be quoted, e.g.:
$type の値は結果セットで返されるーブルの一つまたは複数のデータ型のカンマ 区切りのリストです。 それぞれの値はオプションでクォートされるかもしれません; 例えば:
$type = "TABLE";
$type = "'TABLE','VIEW'";
In addition the following special cases may also be supported by some drivers:
さらにドライバによっては以下の特殊なケースもサポートされているかもしれません。
If the value of $catalog is '%' and $schema and $table name are empty strings, the result set contains a list of catalog names. For example:
$sth = $dbh->table_info('%', '', '');If the value of $schema is '%' and $catalog and $table are empty strings, the result set contains a list of schema names.
If the value of $type is '%' and $catalog, $schema, and $table are all empty strings, the result set contains a list of table types.
If your driver doesn't support one or more of the selection filter parameters then you may get back more than you asked for and can do the filtering yourself.
お使いのドライバが1つまたは複数の選択フィルタパラメータをサポートしていない場合は、要求したよりも多くのパラメータが返される可能性があり、自分でフィルタリングを行うことができます。 (TBR)
This method can be expensive, and can return a large amount of data. (For example, small Oracle installation returns over 2000 rows.) So it's a good idea to use the filters to limit the data as much as possible.
このメソッドはコストがかかり、大量のデータを戻す可能性があります(たとえば、小規模なOracleインストールでは、2000行を超える行が戻されます)。 そのため、フィルタを使用してデータを可能な限り制限することをお薦めします。 (TBR)
The statement handle returned has at least the following fields in the order show below. Other fields, after these, may also be present.
返された行ハンドルは少なくとも後述する順序で以下のフィールドを持ちます。 これらの後に、他のフィールドもあるかもしれません。
TABLE_CAT: Table catalog identifier. This field is NULL (undef) if not applicable to the data source, which is usually the case. This field is empty if not applicable to the table.
TABLE_CAT: テーブルカタログ識別子。 よくあることですが、データソースに適用できなければ、このフィールドが NULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_SCHEM: The name of the schema containing the TABLE_NAME value. This field is NULL (undef) if not applicable to data source, and empty if not applicable to the table.
TABLE_SCHEM: TABLE_NAME値が入っているスキーマの名前です。 データソースに適用できなければ、このフィールドがNULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_NAME: Name of the table (or view, synonym, etc).
TABLE_NAME: テーブル(またはビュー、シノニムなど)の名前。
TABLE_TYPE: One of the following: "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type identifier that is specific to the data source.
TABLE_TYPE: TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" または そのデータソース独自の型識別子のいずれか。
REMARKS: A description of the table. May be NULL (undef).
REMARKS: テーブルの説明。NULL(undef)かもしれません。
Note that table_info might not return records for all tables. Applications can use any valid table regardless of whether it's returned by table_info.
table_info がすべてのテーブルについてレコードを返さないかもしれないことに 注意してください。 table_info により返されたかどうかに関係無く、アプリケーションではすべての 適正なテーブルを扱うことができます。
See also "tables", "Catalog Methods" and "Standards Reference Information".
"tables", "Catalog Methods", "Standards Reference Information" も 参照してください。
column_info¶
$sth = $dbh->column_info( $catalog, $schema, $table, $column );
# then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
Returns an active statement handle that can be used to fetch information about columns in specified tables.
指定された表の行について情報を得るために使える有効な文ハンドルを返します。
The arguments $schema, $table and $column may accept search patterns according to the database/driver, for example: $table = '%FOO%';
引数 $schema, $table, $column はデータベース/ドライバによる検索パターンを 受け付けます; 例えば: $table = '%FOO%';
Note: The support for the selection criteria is driver specific. If the driver doesn't support one or more of them then you may get back more than you asked for and can do the filtering yourself.
注意:選択基準のサポートはドライバ固有です。 ドライバが1つ以上の選択基準をサポートしていない場合は、要求したよりも多くの選択基準が返される可能性があり、自分でフィルタリングを行うことができます。 (TBR)
Note: If your driver does not support column_info an undef is returned. This is distinct from asking for something which does not exist in a driver which supports column_info as a valid statement handle to an empty result-set will be returned in this case.
注意:ドライバがcolumn_infoをサポートしていない場合は、undefが返されます。 これは、column_infoをサポートするドライバに存在しないものを要求することとは異なります。 この場合、空の結果セットへの有効なステートメントハンドルが返されます。 (TBR)
If the arguments don't match any tables then you'll still get a statement handle, it'll just return no rows.
引数がどの表にもマッチングしない場合、単に何の行も返さない 文ハンドルが得られます。
The statement handle returned has at least the following fields in the order shown below. Other fields, after these, may also be present.
返された行ハンドルは少なくとも後述する順序で以下のフィールドを持ちます。 これらの後に、他のフィールドもあるかもしれません。
TABLE_CAT: The catalog identifier. This field is NULL (undef) if not applicable to the data source, which is often the case. This field is empty if not applicable to the table.
TABLE_CAT: カタログ識別子。 よくあることですが、データソースに適用できなければ、このフィールドが NULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_SCHEM: The schema identifier. This field is NULL (undef) if not applicable to the data source, and empty if not applicable to the table.
TABLE_SCHEM: スキーマ識別子。 データソースに適用できなければ、このフィールドがNULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_NAME: The table identifier. Note: A driver may provide column metadata not only for base tables, but also for derived objects like SYNONYMS etc.
TABLE_NAME:表の識別子。 注意:ドライバは、実表の列メタデータのみでなく、SYNONYMSなどの導出オブジェクトの列メタデータも提供できます。 (TBR)
COLUMN_NAME: The column identifier.
COLUMN_NAME: 列識別子。
DATA_TYPE: The concise data type code.
DATA_TYPE: 簡潔なデータ型コード。
TYPE_NAME: A data source dependent data type name.
TYPE_NAME: データソース依存のデータ型名。
COLUMN_SIZE: The column size. This is the maximum length in characters for character data types, the number of digits or bits for numeric data types or the length in the representation of temporal types. See the relevant specifications for detailed information.
COLUMN_SIZE:列のサイズ。 これは、文字データ型の場合は最大文字数、数値データ型の場合は桁数またはビット数、一時データ型の場合は長さです。 詳細は、関連する仕様を参照してください。 (TBR)
BUFFER_LENGTH: The length in bytes of transferred data.
BUFFER_LENGTH: 転送されたデータのバイト数。
DECIMAL_DIGITS: The total number of significant digits to the right of the decimal point.
DECIMAL_DIGITS: 小数点の右側の有効桁数。
NUM_PREC_RADIX: The radix for numeric precision. The value is 10 or 2 for numeric data types and NULL (undef) if not applicable.
NUM_PREC_RADIX:数値精度の基数。 数値データ型の場合、値は10または2です。 該当しない場合は、NULL(undef)です。 (TBR)
NULLABLE: Indicates if a column can accept NULLs. The following values are defined:
NULLABLE: 列が NULL を受け付けるかを示す。 以下の値が定義されています:
SQL_NO_NULLS 0
SQL_NULLABLE 1
SQL_NULLABLE_UNKNOWN 2
REMARKS: A description of the column.
REMARKS: 列の説明。
COLUMN_DEF: The default value of the column, in a format that can be used directly in an SQL statement.
COLUMN_DEF: SQL に直接使える形での、列のデフォルト値。
Note that this may be an expression and not simply the text used for the default value in the original CREATE TABLE statement. For example, given:
これは式になって、元の CREATE TABLE 文のデフォルトとして使われた単純な テキストではないかもしれないことに注意してください。 例えば、以下のようにすると:
col1 char(30) default current_user -- a 'function'
col2 char(30) default 'string' -- a string literal
where "current_user" is the name of a function, the corresponding COLUMN_DEF values would be:
ここで "current_user" が関数名とすると、対応する COLUMN_DEF の値は 以下のようになります:
Database col1 col2
-------- ---- ----
Oracle: current_user 'string'
Postgres: "current_user"() 'string'::text
MS SQL: (user_name()) ('string')
SQL_DATA_TYPE: The SQL data type.
SQL_DATA_TYPE: SQL データ型。
SQL_DATETIME_SUB: The subtype code for datetime and interval data types.
SQL_DATETIME_SUB: 日付時刻と内部データ型のためのサブ型コード。
CHAR_OCTET_LENGTH: The maximum length in bytes of a character or binary data type column.
CHAR_OCTET_LENGTH: 文字やバイナリデータ型列の最大バイト長。
ORDINAL_POSITION: The column sequence number (starting with 1).
ORDINAL_POSITION: 列シーケンス番号 (1 から開始)。
IS_NULLABLE: Indicates if the column can accept NULLs. Possible values are: 'NO', 'YES' and ''.
IS_NULLABLE: 列が NULL を受け付けるかを示す。 取り得る値は: 'NO', 'YES', ''.
SQL/CLI defines the following additional columns:
SQL/CLI は以下の追加の列を定義しています:
CHAR_SET_CAT
CHAR_SET_SCHEM
CHAR_SET_NAME
COLLATION_CAT
COLLATION_SCHEM
COLLATION_NAME
UDT_CAT
UDT_SCHEM
UDT_NAME
DOMAIN_CAT
DOMAIN_SCHEM
DOMAIN_NAME
SCOPE_CAT
SCOPE_SCHEM
SCOPE_NAME
MAX_CARDINALITY
DTD_IDENTIFIER
IS_SELF_REF
Drivers capable of supplying any of those values should do so in the corresponding column and supply undef values for the others.
これらの値のいずれかを提供できるドライバは、対応する列で提供し、他の値にはundef値を提供する必要があります。 (TBR)
Drivers wishing to provide extra database/driver specific information should do so in extra columns beyond all those listed above, and use lowercase field names with the driver-specific prefix (i.e., 'ora_...'). Applications accessing such fields should do so by name and not by column number.
追加のデータベース/ドライバ固有の情報を提供したいドライバは、上記のすべての列に加えて追加の列を提供する必要があります。 また、ドライバ固有の接頭辞('ora_...')を付けた小文字のフィールド名を使用する必要があります。 このようなフィールドにアクセスするアプリケーションは、列番号ではなく名前で提供する必要があります。 (TBR)
The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION.
結果セットは TABLE_CAT, TABLE_SCHEM, TABLE_NAME, ORDINAL_POSITION で ソートされます。
Note: There is some overlap with statement handle attributes (in perl) and SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata.
注意: (perl での)文ハンドル属性と (ODBC での) SQLDescribeCol には 重複があります。 しかし、SQLDescribeCol はさらなるメタデータを提供します。
See also "Catalog Methods" and "Standards Reference Information".
"Catalog Methods" と "Standards Reference Information" も 参照してください。
primary_key_info¶
$sth = $dbh->primary_key_info( $catalog, $schema, $table );
# then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
Returns an active statement handle that can be used to fetch information about columns that make up the primary key for a table. The arguments don't accept search patterns (unlike table_info()).
テーブルのための主キーとして設定されているカラムについての情報を 取り出すために使われる Active な文・ハンドルを返します。 引数に検索パターンは受け取りません(table_info()とは違って)。
The statement handle will return one row per column, ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ. If there is no primary key then the statement handle will fetch no rows.
ステートメントハンドルは、TABLE_CAT、TABLE_SCHEMA、TABLE_NAMEおよびKEY_SEQの順序で、列ごとに1行を戻します。 プライマリキーがない場合、ステートメントハンドルは行をフェッチしません。 (TBR)
Note: The support for the selection criteria, such as $catalog, is driver specific. If the driver doesn't support catalogs and/or schemas, it may ignore these criteria.
注意:$catalog のような、選択条件のサポートはドライバによります。 もしドライバがカタログやスキーマをサポートしていなければ、これらの条件は 無視されるかもしれません。
The statement handle returned has at least the following fields in the order shown below. Other fields, after these, may also be present.
返された行ハンドルは少なくとも後述する順序で以下のフィールドを持ちます。 これらの後に、他のフィールドもあるかもしれません。
TABLE_CAT: The catalog identifier. This field is NULL (undef) if not applicable to the data source, which is often the case. This field is empty if not applicable to the table.
TABLE_CAT: カタログ識別子。 よくあることですが、データソースに適用できなければ、このフィールドが NULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_SCHEM: The schema identifier. This field is NULL (undef) if not applicable to the data source, and empty if not applicable to the table.
TABLE_SCHEM: スキーマ識別子。 データソースに適用できなければ、このフィールドがNULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_NAME: The table identifier.
TABLE_NAME: テーブル識別子。
COLUMN_NAME: The column identifier.
COLUMN_NAME: 列識別子。
KEY_SEQ: The column sequence number (starting with 1). Note: This field is named ORDINAL_POSITION in SQL/CLI.
KEY_SEQ: カラム順序番号(1始まり)。 注意:SQL/CLI ではこのフィールドは ORDINAL_POSITION と名づけられています。
PK_NAME: The primary key constraint identifier. This field is NULL (undef) if not applicable to the data source.
PK_NAME: 主キー制約識別子。 データソースに適用できなければ NULL(undef) です。
See also "Catalog Methods" and "Standards Reference Information".
"Catalog Methods" と "Standards Reference Information" も 参照してください。
primary_key¶
@key_column_names = $dbh->primary_key( $catalog, $schema, $table );
Simple interface to the primary_key_info() method. Returns a list of the column names that comprise the primary key of the specified table. The list is in primary key column sequence order. If there is no primary key then an empty list is returned.
primary_key_info() メソッドへの単純なインターフェースです。 指定されたテーブルの主キーを含むカラム目のリストを返します。 このリストは主キーカラム順番号順に入ります。 主キーがない場合、空リストが返されます。
foreign_key_info¶
$sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
, $fk_catalog, $fk_schema, $fk_table );
$sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
, $fk_catalog, $fk_schema, $fk_table
, \%attr );
# then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
Returns an active statement handle that can be used to fetch information about foreign keys in and/or referencing the specified table(s). The arguments don't accept search patterns (unlike table_info()).
指定されたテーブル内の外部キーに関する情報を取得したり、指定されたテーブルを参照するために使用できる、アクティブなステートメントハンドルを返します。 この引数は検索パターンを受け付けません(table_info()と異なります)。 (TBR)
$pk_catalog, $pk_schema, $pk_table identify the primary (unique) key table (PKT).
$pk_catalog, $pk_schema, $pk_table は主(ユニーク)キー表 (PKT) を識別します。
$fk_catalog, $fk_schema, $fk_table identify the foreign key table (FKT).
$fk_catalog, $fk_schema, $fk_table は外部キー表 (FKT) を 識別します。
If both PKT and FKT are given, the function returns the foreign key, if any, in table FKT that refers to the primary (unique) key of table PKT. (Note: In SQL/CLI, the result is implementation-defined.)
PKTとFKTの両方が指定された場合、テーブルPKTのプライマリ(一意の)キーを参照する外部キーがテーブルFKTに存在する場合、この関数は外部キーを返します。 (注:SQL/CLIでは、結果は実装によって定義されます。 ) (TBR)
If only PKT is given, then the result set contains the primary key of that table and all foreign keys that refer to it.
PKT のみが指定されると、結果セットにはその表の主キーと、それを 参照している全ての外部キーが含まれます。
If only FKT is given, then the result set contains all foreign keys in that table and the primary keys to which they refer. (Note: In SQL/CLI, the result includes unique keys too.)
FKTのみが指定された場合、結果セットには、そのテーブル内のすべての外部キーと、それらが参照するプライマリキーが含まれます(注:SQL/CLIでは、結果にはユニークキーも含まれます)。 (TBR)
For example:
例えば:
$sth = $dbh->foreign_key_info( undef, $user, 'master');
$sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail');
$sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail');
# then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
Note: The support for the selection criteria, such as $catalog, is driver specific. If the driver doesn't support catalogs and/or schemas, it may ignore these criteria.
注意:$catalogなどの選択基準のサポートはドライバ固有です。 ドライバがカタログやスキーマをサポートしていない場合は、これらの基準が無視される可能性があります。 (TBR)
The statement handle returned has the following fields in the order shown below. Because ODBC never includes unique keys, they define different columns in the result set than SQL/CLI. SQL/CLI column names are shown in parentheses.
戻されたステートメントハンドルには、次に示す順序で次のフィールドがあります。 ODBCには一意のキーが含まれないため、結果セットにはSQL/CLIとは異なる列が定義されます。 SQL/CLIの列名はカッコ内に表示されます。 (TBR)
PKTABLE_CAT ( UK_TABLE_CAT ): The primary (unique) key table catalog identifier. This field is NULL (undef) if not applicable to the data source, which is often the case. This field is empty if not applicable to the table.
PKTABLE_CAT ( UK_TABLE_CAT ):主(一意の)キーテーブルカタログ識別子。 このフィールドは、データソースに適用されない場合はNULL(undef)です。 このフィールドは、テーブルに適用されない場合は空です。 (TBR)
PKTABLE_SCHEM ( UK_TABLE_SCHEM ): The primary (unique) key table schema identifier. This field is NULL (undef) if not applicable to the data source, and empty if not applicable to the table.
PKTABLE_SCHEMA(UK_TABLE_SCHEMA):主(一意の)キーテーブルスキーマ識別子。 このフィールドは、データソースに適用できない場合はNULL(undef)、テーブルに適用できない場合は空です。 (TBR)
PKTABLE_NAME ( UK_TABLE_NAME ): The primary (unique) key table identifier.
PKTABLE_NAME ( UK_TABLE_NAME ): 主(ユニーク)キー表識別子。
PKCOLUMN_NAME (UK_COLUMN_NAME ): The primary (unique) key column identifier.
PKCOLUMN_NAME (UK_COLUMN_NAME ): 主(ユニーク)キー列識別子。
FKTABLE_CAT ( FK_TABLE_CAT ): The foreign key table catalog identifier. This field is NULL (undef) if not applicable to the data source, which is often the case. This field is empty if not applicable to the table.
FKTABLE_CAT ( FK_TABLE_CAT ):外部キーテーブルカタログ識別子。 このフィールドは、データソースに適用できない場合はNULL(undef)です。 このフィールドは、テーブルに適用できない場合は空です。 (TBR)
FKTABLE_SCHEM ( FK_TABLE_SCHEM ): The foreign key table schema identifier. This field is NULL (undef) if not applicable to the data source, and empty if not applicable to the table.
FKTABLE_SCHEMA(FK_TABLE_SCHEMA):外部キーテーブルスキーマ識別子。 このフィールドは、データソースに適用できない場合はNULL(undef)、テーブルに適用できない場合は空です。 (TBR)
FKTABLE_NAME ( FK_TABLE_NAME ): The foreign key table identifier.
FKTABLE_NAME ( FK_TABLE_NAME ): 外部キー表識別子。
FKCOLUMN_NAME ( FK_COLUMN_NAME ): The foreign key column identifier.
FKCOLUMN_NAME ( FK_COLUMN_NAME ): 外部キー列識別子。
KEY_SEQ ( ORDINAL_POSITION ): The column sequence number (starting with 1).
KEY_SEQ ( ORDINAL_POSITION ): 列シーケンス番号(1 から開始)。
UPDATE_RULE ( UPDATE_RULE ): The referential action for the UPDATE rule. The following codes are defined:
UPDATE_RULE ( UPDATE_RULE ):UPDATEルールの参照アクション。 次のコードが定義されています。 (TBR)
CASCADE 0
RESTRICT 1
SET NULL 2
NO ACTION 3
SET DEFAULT 4
DELETE_RULE ( DELETE_RULE ): The referential action for the DELETE rule. The codes are the same as for UPDATE_RULE.
DELETE_RULE ( DELETE_RULE ):DELETEルールの参照アクション。 コードはUPDATE_RULEのものと同じです。 (TBR)
FK_NAME ( FK_NAME ): The foreign key name.
FK_NAME ( FK_NAME ): 外部キー名。
PK_NAME ( UK_NAME ): The primary (unique) key name.
PK_NAME ( UK_NAME ): 主 (ユニーク) キー名。
DEFERRABILITY ( DEFERABILITY ): The deferrability of the foreign key constraint. The following codes are defined:
DEFERRABILITY(DEFERRABILITY):外部キー制約の遅延可能性。 次のコードが定義されています。 (TBR)
INITIALLY DEFERRED 5
INITIALLY IMMEDIATE 6
NOT DEFERRABLE 7
( UNIQUE_OR_PRIMARY ): This column is necessary if a driver includes all candidate (i.e. primary and alternate) keys in the result set (as specified by SQL/CLI). The value of this column is UNIQUE if the foreign key references an alternate key and PRIMARY if the foreign key references a primary key, or it may be undefined if the driver doesn't have access to the information.
( UNIQUE_OR_PRIMARY ):この列は、ドライバの結果セットにすべての候補キー(主キーと代替キー)が含まれている場合に必要です(SQL/CLIで指定)。 この列の値は、外部キーが代替キーを参照している場合はUNIQUE、外部キーが主キーを参照している場合はPRIMARYです。 ドライバが情報にアクセスできない場合は、未定義になることがあります。 (TBR)
See also "Catalog Methods" and "Standards Reference Information".
"Catalog Methods" と "Standards Reference Information" も 参照してください。
statistics_info¶
Warning: This method is experimental and may change.
警告: このメソッドは実験的であり変更されるかもしれません。
$sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick );
# then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
Returns an active statement handle that can be used to fetch statistical information about a table and its indexes.
表とそのインデックスに関する統計情報を取得するのに使える、有効な 文ハンドルを返します。
The arguments don't accept search patterns (unlike "table_info").
引数は ("table_info" と違って) 検索パターンは受け付けません。
If the boolean argument $unique_only is true, only UNIQUE indexes will be returned in the result set, otherwise all indexes will be returned.
真偽値引数 $unique_only が真なら、ユニークインデックスのみが 結果セットで返され、さもなければ全てのインデックスが返されます。
If the boolean argument $quick is set, the actual statistical information columns (CARDINALITY and PAGES) will only be returned if they are readily available from the server, and might not be current. Some databases may return stale statistics or no statistics at all with this flag set.
ブール値の引数$quickが設定されている場合、実際の統計情報の列(CARDINALITYおよびPAGES)が返されるのは、それらの列がサーバーからすぐに利用できる場合のみで、最新のものではない可能性があります。 データベースによっては、このフラグを設定すると、古い統計情報が返されたり、統計情報がまったく返されない場合があります。 (TBR)
The statement handle will return at most one row per column name per index, plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION.
ステートメントハンドルは、NON_UNIQUE、TYPE、INDEX_QUALIFIER、INDEX_NAME、およびORDINAL_POSITIONの順序で、インデックスごとに列名ごとに最大1つのローと、テーブル全体で最大1つのローを返します。 (TBR)
Note: The support for the selection criteria, such as $catalog, is driver specific. If the driver doesn't support catalogs and/or schemas, it may ignore these criteria.
注意:$catalog のような、選択条件のサポートはドライバによります。 もしドライバがカタログやスキーマをサポートしていなければ、これらの条件は 無視されるかもしれません。
The statement handle returned has at least the following fields in the order shown below. Other fields, after these, may also be present.
返された行ハンドルは少なくとも後述する順序で以下のフィールドを持ちます。 これらの後に、他のフィールドもあるかもしれません。
TABLE_CAT: The catalog identifier. This field is NULL (undef) if not applicable to the data source, which is often the case. This field is empty if not applicable to the table.
TABLE_CAT: カタログ識別子。 よくあることですが、データソースに適用できなければ、このフィールドが NULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_SCHEM: The schema identifier. This field is NULL (undef) if not applicable to the data source, and empty if not applicable to the table.
TABLE_SCHEM: スキーマ識別子。 データソースに適用できなければ、このフィールドがNULL(undef)です。 テーブルに適用できなければ、このフィールドは空です。
TABLE_NAME: The table identifier.
TABLE_NAME: テーブル識別子。
NON_UNIQUE: Unique index indicator. Returns 0 for unique indexes, 1 for non-unique indexes
NON_UNIQUE: ユニークインデックス指示子。 ユニークインデックスの場合は 0 を、それ以外のインデックスでは 1 を 返します。
INDEX_QUALIFIER: Index qualifier identifier. The identifier that is used to qualify the index name when doing a DROP INDEX; NULL (undef) is returned if an index qualifier is not supported by the data source. If a non-NULL (defined) value is returned in this column, it must be used to qualify the index name on a DROP INDEX statement; otherwise, the TABLE_SCHEM should be used to qualify the index name.
INDEX_QUALIFIER:索引クオリファイア識別子。 DROP INDEXの実行時に索引名の修飾に使用される識別子。 データソースで索引クオリファイアがサポートされていない場合は、NULL(undef)が戻されます。 この列にNULL(定義済)以外の値が戻された場合は、その値を使用してDROP INDEX文の索引名を修飾する必要があります。 それ以外の場合は、TABLE_SCHEMAを使用して索引名を修飾する必要があります。 (TBR)
INDEX_NAME: The index identifier.
INDEX_NAME: インデックス識別子。
TYPE: The type of information being returned. Can be any of the following values: 'table', 'btree', 'clustered', 'content', 'hashed', or 'other'.
TYPE:戻される情報のタイプ。 'table'、'btree'、'clustered'、'content'、'hashed'、または'other'のいずれかの値になります。 (TBR)
In the case that this field is 'table', all fields other than TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE, CARDINALITY, and PAGES will be NULL (undef).
このフィールドが'table'の場合、TABLE_CAT、TABLE_SCHEMA、TABLE_NAME、TYPE、CARDINALITY、およびPAGES以外のすべてのフィールドはNULL(undef)になります。 (TBR)
ORDINAL_POSITION: Column sequence number (starting with 1).
ORDINAL_POSITION: 列シーケンス番号 (1 から開始)。
COLUMN_NAME: The column identifier.
COLUMN_NAME: 列識別子。
ASC_OR_DESC: Column sort sequence. A for Ascending, D for Descending, or NULL (undef) if not supported for this index.
ASC_OR_DESC:列のソート順序。 昇順の場合はA、降順の場合はD、この索引でサポートされていない場合はNULL(undef)。 (TBR)
CARDINALITY: Cardinality of the table or index. For indexes, this is the number of unique values in the index. For tables, this is the number of rows in the table. If not supported, the value will be NULL (undef).
CARDINALITY:表または索引のカーディナリティ。 索引の場合、これは索引内の一意の値の数です。 表の場合、これは表の行数です。 サポートされていない場合、値はNULL(undef)になります。 (TBR)
PAGES: Number of storage pages used by this table or index. If not supported, the value will be NULL (undef).
PAGES: この表またはインデックスで使われるページ番号。 対応していない場合は、値は NULL (undef) になります。
FILTER_CONDITION: The index filter condition as a string. If the index is not a filtered index, or it cannot be determined whether the index is a filtered index, this value is NULL (undef). If the index is a filtered index, but the filter condition cannot be determined, this value is the empty string ''. Otherwise it will be the literal filter condition as a string, such as SALARY <= 4500.
FILTER_CONDITION:文字列としてのインデックスフィルタ条件。 インデックスがフィルタされたインデックスでない場合、またはインデックスが フィルタされたインデックスであるかどうかを判別できない場合、 この値はNULL(undef)です。 インデックスがフィルタされたインデックスであるが、フィルタ条件を 判別できない場合、この値は空の文字列''です。 それ以外の場合は、文字列としてのリテラルフィルタ条件 (SALARY <= 4500など)になります。 (TBR)
See also "Catalog Methods" and "Standards Reference Information".
"Catalog Methods" と "Standards Reference Information" も 参照してください。
tables¶
@names = $dbh->tables( $catalog, $schema, $table, $type );
@names = $dbh->tables; # deprecated
Simple interface to table_info(). Returns a list of matching table names, possibly including a catalog/schema prefix.
table_info()への単純なインターフェースです。 テーブル、ビューの名前の単純なリストを返します; おそらく頭にスキーマがついてきます。
See "table_info" for a description of the parameters.
パラメータの説明については "table_info" を参照してください。
If $dbh->get_info(29) returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR) then the table names are constructed and quoted by "quote_identifier" to ensure they are usable even if they contain whitespace or reserved words etc. This means that the table names returned will include quote characters.
$dbh->get_info(29)がtrueを返す場合(29はSQL_IDENTIFIER_QUOTE_CHAR)、空白や予約語などが含まれていても使用できるように、テーブル名は"quote_identifier"で構成され、引用符で囲まれます。 これは、返されるテーブル名に引用符文字が含まれることを意味します。 (TBR)
type_info_all¶
$type_info_all = $dbh->type_info_all;
Returns a reference to an array which holds information about each data type variant supported by the database and driver. The array and its contents should be treated as read-only.
データベースあるいはドライバによりサポートされるデータ型についての情報が 入った配列へのリファレンスを返します。 配列及びその内容は読み込み専用として扱われなければなりません。
The first item is a reference to an 'index' hash of Name => Index pairs. The items following that are references to arrays, one per supported data type variant. The leading index hash defines the names and order of the fields within the arrays that follow it. For example:
最初の要素は 名前 = > インデックスというペアのハッシュへの リファレンスです。 その後の要素は、配列へのリファレンスで、1つずつがサポートされている データ型になります。 最初のハッシュが後に続く配列要素のフィールドの名前と順序を定義しています。 例:
$type_info_all = [
{ TYPE_NAME => 0,
DATA_TYPE => 1,
COLUMN_SIZE => 2, # was PRECISION originally
LITERAL_PREFIX => 3,
LITERAL_SUFFIX => 4,
CREATE_PARAMS => 5,
NULLABLE => 6,
CASE_SENSITIVE => 7,
SEARCHABLE => 8,
UNSIGNED_ATTRIBUTE=> 9,
FIXED_PREC_SCALE => 10, # was MONEY originally
AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
LOCAL_TYPE_NAME => 12,
MINIMUM_SCALE => 13,
MAXIMUM_SCALE => 14,
SQL_DATA_TYPE => 15,
SQL_DATETIME_SUB => 16,
NUM_PREC_RADIX => 17,
INTERVAL_PRECISION=> 18,
},
[ 'VARCHAR', SQL_VARCHAR,
undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
],
[ 'INTEGER', SQL_INTEGER,
undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
],
];
More than one row may have the same value in the DATA_TYPE field if there are different ways to spell the type name and/or there are variants of the type with different attributes (e.g., with and without AUTO_UNIQUE_VALUE set, with and without UNSIGNED_ATTRIBUTE, etc).
その型の名前に違った書き方があったり、属性の違いで型のバリエーションが あったり(例えば AUTO_UNIQUE_VALUE があったりなかったり、 UNSIGNED_ATTRIBUTE があったりなかったりなど)すれば、一つ以上のフィールドが DATA_TYPE フィールドに同じ値をもつこともあることに注意してください。
The rows are ordered by DATA_TYPE first and then by how closely each type maps to the corresponding ODBC SQL data type, closest first.
行はまず DATA_TYPE で順に、そして ODBC SQL データ型にどれくらい近く 対応しているかによって近いほど先に順に並びます。
The meaning of the fields is described in the documentation for the "type_info" method.
各フィールドの意味は "type_info" メソッドで説明しています。
An 'index' hash is provided so you don't need to rely on index values defined above. However, using DBD::ODBC with some old ODBC drivers may return older names, shown as comments in the example above. Another issue with the index hash is that the lettercase of the keys is not defined. It is usually uppercase, as show here, but drivers may return names with any lettercase.
'index' ハッシュが提供されるので、上で定義されているインデックス値に 頼る必要はありません。 しかし、古い ODBC ドライバで DBD::ODBC を使うと、上述の例のコメントに あるように、古い名前を返すかもしれません。 インデックスハッシュに関するもう一つの問題は、キーの大文字小文字が 未定義であることです。 それは通常、ここで見てきたように大文字ですが、ドライバは名前を大文字、 小文字のどちらで返しても自由です。
Drivers are also free to return extra driver-specific columns of information - though it's recommended that they start at column index 50 to leave room for expansion of the DBI/ODBC specification.
ドライバは特別なドライバ専用の情報のカラムを返すのも自由です - しかし DBI/ODBC 仕様の拡張のための空間をあけておくためにカラムインデックス 50 から 始めることをお勧めします。
The type_info_all() method is not normally used directly. The "type_info" method provides a more usable and useful interface to the data.
type_info_all()メソッドは通常直接使用されません。 "type_info"メソッドは、データへのより使用可能で有用なインタフェースを提供します。 (TBR)
type_info¶
@type_info = $dbh->type_info($data_type);
Returns a list of hash references holding information about one or more variants of $data_type. The list is ordered by DATA_TYPE first and then by how closely each type maps to the corresponding ODBC SQL data type, closest first. If called in a scalar context then only the first (best) element is returned.
一つあるいは複数の $data_type の変形についての情報が入ったハッシュへの リファレンスのリストが返されます。 リストはまず DATA_TYPE によって並べられ、そして各型が ODBC SQL データ型に どらくらい近く対応しているかによって近いほど先に順に並びます。 スカラコンテキストで呼ばれれば、最初の(もっともよい)要素だけが返されます。
If $data_type is undefined or SQL_ALL_TYPES, then the list will contain hashes for all data type variants supported by the database and driver.
$data_type が未定義か SQL_ALL_TYPES であれば、リストにはデータベースと ドライバによってサポートされているすべてのデータ型が入ります。
If $data_type is an array reference then type_info returns the information for the first type in the array that has any matches.
もし $data_type が配列リファレンスであれば、type_info はその配列の いずれかが対応する最初の型のための情報を返します。
The keys of the hash follow the same letter case conventions as the rest of the DBI (see "Naming Conventions and Name Space"). The following uppercase items should always exist, though may be undef:
以下のハッシュのキーは DBI の他の部分と同じようにすべて大文字もしくは 小文字で表わされます。 ("Naming Conventions and Name Space" をご覧ください)。 以下に示す大文字要素は間違い無く存在しますが、未定義かもしれません:
- TYPE_NAME (string)
-
Data type name for use in CREATE TABLE statements etc.
CREATE TABLE 文などで使われるデータ型名。
- DATA_TYPE (integer)
-
SQL data type number.
SQL データ型番号。
- COLUMN_SIZE (integer)
-
For numeric types, this is either the total number of digits (if the NUM_PREC_RADIX value is 10) or the total number of bits allowed in the column (if NUM_PREC_RADIX is 2).
数値型については、これは(NUM_PREC_RADIX の値が 10 であれば)総桁数、 もしくは(NUM_PREC_RADIX の値が 2 であれば)カラムの中に許されるビットの 総数。
For string types, this is the maximum size of the string in characters.
文字列型であれば、これは文字列の最大サイズを文字数で表したもの。
For date and interval types, this is the maximum number of characters needed to display the value.
日付(date)および期間(interval)型であれば、その値を表示するために必要な文字の 最大数です。
- LITERAL_PREFIX (string)
-
Characters used to prefix a literal. A typical prefix is "
'" for characters, or possibly "0x" for binary values passed as hexadecimal. NULL (undef) is returned for data types for which this is not applicable.リテラルの最初に使われる文字。 典型的なものとしては文字型には "
'"、バイナリ値には 16 進数を表わす "0x"。 このデータ型に当てはまらなければ、NULL (undef) が返されます。 - LITERAL_SUFFIX (string)
-
Characters used to suffix a literal. Typically "
'" for characters. NULL (undef) is returned for data types where this is not applicable.リテラルの最後に使われる文字。 典型的なものとしては文字型には "
'"。 このデータ型に当てはまらなければ、NULL (undef)。 - CREATE_PARAMS (string)
-
Parameter names for data type definition. For example,
CREATE_PARAMSfor aDECIMALwould be "precision,scale" if the DECIMAL type should be declared asDECIMAL(precision,scale)where precision and scale are integer values. For aVARCHARit would be "max length". NULL (undef) is returned for data types for which this is not applicable.データ型定義のためのパラメータ名。 例えば
DECIMALがDECIMAL(precision,scale)(全体桁数,小数点以下桁数)、 precision と scale は整数値のように宣言されなければならないのであれば、DECIMALのためのCREATE_PARAMSは "precision,scale" になります。VARCHARでは "max length"(最大長)になります。 このデータ型に当てはまらなければ、NULL (undef) が返されます。 - NULLABLE (integer)
-
Indicates whether the data type accepts a NULL value:
0or an empty string = no,1= yes,2= unknown.このデータ型がNULL値を受け入れるかどうかを示します: (
0または空文字列 = 受け入れない,1= 受け入れる,2= 不明) - CASE_SENSITIVE (boolean)
-
Indicates whether the data type is case sensitive in collations and comparisons.
このデータ型が照会や比較のさいに大文字、小文字を区別するかどうかを示します。
- SEARCHABLE (integer)
-
Indicates how the data type can be used in a WHERE clause, as follows:
データタイプが WHERE 句で以下のように使用できるかどうかを示します:
0 - Cannot be used in a WHERE clause 1 - Only with a LIKE predicate 2 - All comparison operators except LIKE 3 - Can be used in a WHERE clause with any comparison operator
0 - WHERE 句で使うことはできません
1 - LIKE と一緒になら使えます。
2 - LIKE を除いてすべての比較演算子が使えます
3 - WHERE 句においてすべての比較演算子が使えます
Indicates whether the data type is unsigned. NULL (undef) is returned for data types for which this is not applicable.
データ型が符号なしであるかどうかを示します。 このデータ型に当てはまらなければ、NULL (undef) が返されます。
Indicates whether the data type always has the same precision and scale (such as a money type). NULL (undef) is returned for data types for which this is not applicable.
そのデータ型が(money 型のように)常に同じ精度、桁数を持つかどうかを 示します。 このデータ型に当てはまらなければ、NULL (undef) が返されます。
Indicates whether a column of this data type is automatically set to a unique value whenever a new row is inserted. NULL (undef) is returned for data types for which this is not applicable.
新しい行が挿入するときにはいつも、このデータ型のカラムは自動的に ユニークな値に設定されるかどうかを示します。 このデータ型に当てはまらなければ、NULL (undef) が返されます。
Localized version of the TYPE_NAME for use in dialog with users. NULL (undef) is returned if a localized name is not available (in which case TYPE_NAME should be used).
ユーザとの対話に使われる TYPE_NAME のローカル化されたバージョン。 ローカル化された名前がなければNULL (undef)(この場合は TYPE_NAME を 使わなければなりません)。
The minimum scale of the data type. If a data type has a fixed scale, then MAXIMUM_SCALE holds the same value. NULL (undef) is returned for data types for which this is not applicable.
データ型の最小桁数。 データ型が決まった桁数をもっていれば、MAXIMUM_SCALE と同じになります。 このデータ型に当てはまらなければ、NULL (undef) が返されます。
The maximum scale of the data type. If a data type has a fixed scale, then MINIMUM_SCALE holds the same value. NULL (undef) is returned for data types for which this is not applicable.
データ型の最大桁数。 データ型が決まった桁数をもっていれば、MINIMUM_SCALE と同じになります。 このデータ型に当てはまらなければ、NULL (undef) が返されます。
This column is the same as the DATA_TYPE column, except for interval and datetime data types. For interval and datetime data types, the SQL_DATA_TYPE field will return SQL_INTERVAL or SQL_DATETIME, and the SQL_DATETIME_SUB field below will return the subcode for the specific interval or datetime data type. If this field is NULL, then the driver does not support or report on interval or datetime subtypes.
期間(interval)と日時(datetime)型を除いては、このカラムは DATA_TYPE と 同じです。 期間(interval)と日時(datetime)型であれば、SQL_DATA_TYPE は SQL_INTERVAL もしくは SQL_DATETIME を返し、以下の SQL_DATETIME_SUB は 特定の期間(interval)または日時(datetime)型のためのサブコードを返します。 もしこのフィールドが NULL であれば、ドライバは期間(interval)または 日時(datetime)型をサポートしていないか、報告しません。
For interval or datetime data types, where the SQL_DATA_TYPE field above is SQL_INTERVAL or SQL_DATETIME, this field will hold the subcode for the specific interval or datetime data type. Otherwise it will be NULL (undef).
期間(interval)と日時(datetime)型であれば、上記の SQL_DATA_TYPE は SQL_INTERVAL もしくは SQL_DATETIME を返し、 このフィールドは特定の期間(interval)または日時(datetime)型のための サブコードを返します。 そうでなければNULL(undef)になります。
Although not mentioned explicitly in the standards, it seems there is a simple relationship between these values:
標準には明示的に記述されていませんが、これらの値には単純な関係が あるようです:
DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB
The radix value of the data type. For approximate numeric types, NUM_PREC_RADIX contains the value 2 and COLUMN_SIZE holds the number of bits. For exact numeric types, NUM_PREC_RADIX contains the value 10 and COLUMN_SIZE holds the number of decimal digits. NULL (undef) is returned either for data types for which this is not applicable or if the driver cannot report this information.
そのデータ型の基数を返します。 概算の数値型では、NUM_PREC_RADIX の値は 2 で COLUMN_SIZE はビットの数を 持ちます。 厳密な数値型では NUM_PREC_RADIX の値は 10 で、COLUMN_SIZE には 10 進数の桁数が入ります。 このデータ型に当てはまらないか、ドライバがこの情報を報告できなければ、 NULL (undef) が返されます。
The interval leading precision for interval types. NULL is returned either for data types for which this is not applicable or if the driver cannot report this information.
期間(interval)型のための先行精度です。 このデータ型に当てはまらないか、ドライバがこの情報を報告できなければ、 NULL (undef) が返されます。
For example, to find the type name for the fields in a select statement you can do:
例えば select 文でのフィールドのためのデータ型名を見つけるには 以下のようにすることができます:
@names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
Since DBI and ODBC drivers vary in how they map their types into the ISO standard types you may need to search for more than one type. Here's an example looking for a usable type to store a date:
DBI と ODBC ドライバとは型を ISO 標準型にどのようにマッピングするのかが 異なっているため、一つ以上の型を探さなければならないかもしれません。 以下に日付を格納するのに使えるデータ型を探す例を示します:
$my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
Similarly, to more reliably find a type to store small integers, you could use a list starting with SQL_SMALLINT, SQL_INTEGER, SQL_DECIMAL, etc.
同じように、小さな整数を格納するための型の検索を信頼できるようにするため、 SQL_SMALLINT, SQL_INTEGER, SQL_DECIMAL などから始まるリストを 使うこともできます。
See also "Standards Reference Information".
"Standards Reference Information" も参照してください。
quote¶
$sql = $dbh->quote($value);
$sql = $dbh->quote($value, $data_type);
Quote a string literal for use as a literal value in an SQL statement, by escaping any special characters (such as quotation marks) contained within the string and adding the required type of outer quotation marks.
文字列の中の(クォーテーションマークのような)特殊な文字をエスケープし、 必要とされるタイプの外側のクォーテーションマークを加えることにより、 文字列リテラルを SQL 文で使うリテラル値として使えるようにクォートします。
$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
$dbh->quote("Don't");
For most database types, at least those that conform to SQL standards, quote would return 'Don''t' (including the outer quotation marks). For others it may return something like 'Don\'t'
ほとんどのデータベースでは、少なくとも SQL 標準に従っているものなら、 quote は 'Don"t' を返します(外側のクォーテーションマークを含みます)。 その他の場合は 'Don\'t' のようなものを返します。
An undefined $value value will be returned as the string NULL (without single quotation marks) to match how NULLs are represented in SQL.
未定義の $value の値は SQL で NULL を表すことに対応するよう、文字列 NULL (シングルクォーテションマークなし)になります。
If $data_type is supplied, it is used to try to determine the required quoting behaviour by using the information returned by "type_info". As a special case, the standard numeric types are optimized to return $value without calling type_info.
$data_type が与えられると、"type_info" から返される情報を元にして 要求されたクォートの処理を決めます。 特殊な場合として、標準の数値型は type_info を呼ばずに、$value を 返すように最適化されています。
Quote will probably not be able to deal with all possible input (such as binary data or data containing newlines), and is not related in any way with escaping or quoting shell meta-characters.
quote は(バイナリデータや改行が入っているデータのように)すべての入力に 対応できるわけではありません; そしてシェルのエスケープやメタ文字にはまったく 関連してはいません。
It is valid for the quote() method to return an SQL expression that evaluates to the desired string. For example:
必要な文字列を評価する SQL 式を返すための quote() メソッドも有効です。 例えば:
$quoted = $dbh->quote("one\ntwo\0three")
may return something like:
というものは以下のようなものを返します:
CONCAT('one', CHAR(12), 'two', CHAR(0), 'three')
The quote() method should not be used with "Placeholders and Bind Values".
quote() メソッドは "Placeholders and Bind Values" と使うべきでは ありません 。
quote_identifier¶
$sql = $dbh->quote_identifier( $name );
$sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr );
Quote an identifier (table name etc.) for use in an SQL statement, by escaping any special characters (such as double quotation marks) it contains and adding the required type of outer quotation marks.
SQL文で使用する識別子(テーブル名など)を引用符で囲むには、識別子に含まれる特殊文字(二重引用符など)をエスケープし、必要なタイプの外部引用符を追加します。 (TBR)
Undefined names are ignored and the remainder are quoted and then joined together, typically with a dot (.) character. For example:
未定義の名前は無視され、残りはクォートされてから互いに (典型的にはドット (.) 文字で)結合されます。 例えば:
$id = $dbh->quote_identifier( undef, 'Her schema', 'My table' );
would, for most database types, return "Her schema"."My table" (including all the double quotation marks).
というのは、ほとんどのデータベース型では、 "Her schema"."My table" (ダブルクォートを含みます) を返します。
If three names are supplied then the first is assumed to be a catalog name and special rules may be applied based on what "get_info" returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114). For example, for Oracle:
3つの名前が指定された場合、最初の名前はカタログ名と見なされ、"get_info"がSQL_CATALOG_NAME_SEPARATOR(41)およびSQL_CATALOG_LOCATION(114)に対して返す内容に基づいて特別なルールが適用される場合があります。 たとえば、Oracleの場合は次のようになります。 (TBR)
$id = $dbh->quote_identifier( 'link', 'schema', 'table' );
would return "schema"."table"@"link".
は "schema"."table"@"link" を返します。
take_imp_data¶
$imp_data = $dbh->take_imp_data;
Leaves the $dbh in an almost dead, zombie-like, state and returns a binary string of raw implementation data from the driver which describes the current database connection. Effectively it detaches the underlying database API connection data from the DBI handle. After calling take_imp_data(), all other methods except DESTROY will generate a warning and return undef.
$dbhをほとんど動かない、ゾンビのような状態のままにして、現在のデータベース接続を記述するドライバからの生の実装データのバイナリ文字列を返します。 実質的に、基礎となるデータベースAPI接続データをDBIハンドルから切り離します。 take_imp_data()を呼び出した後、DESTROYを除く他のすべてのメソッドは警告を生成し、undefを返します。 (TBR)
Why would you want to do this? You don't, forget I even mentioned it. Unless, that is, you're implementing something advanced like a multi-threaded connection pool. See DBI::Pool.
なぜあなたはこれをしたいのですか?あなたはしません、私がそれを言ったことさえ忘れてください。 ただし、マルチスレッド接続プールのような高度なものを実装している場合は除きます。 DBI::Poolを参照してください。 (TBR)
The returned $imp_data can be passed as a dbi_imp_data attribute to a later connect() call, even in a separate thread in the same process, where the driver can use it to 'adopt' the existing connection that the implementation data was taken from.
返された$imp_dataは、後のconnect()呼び出しにCの<dbi_imp_data>属性として渡すことができます。 同じプロセス内の別のスレッドであってもかまいません。 ドライバは、この属性を使用して、実装データが取得された既存の接続を「採用」できます。 (TBR)
Some things to keep in mind...
覚えておくべきことは…
* the $imp_data holds the only reference to the underlying database API connection data. That connection is still 'live' and won't be cleaned up properly unless the $imp_data is used to create a new $dbh which is then allowed to disconnect() normally.
*$imp_dataは、基礎となるデータベースAPI接続データへの唯一の参照を保持しています。 この接続はまだ「有効」であり、$imp_dataを使用して新しい$dbhを作成し、通常どおりdisconnect()できるようにしない限り、適切にクリーンアップされません。 (TBR)
* using the same $imp_data to create more than one other new $dbh at a time may well lead to unpleasant problems. Don't do that.
*同じ$imp_dataを使用して一度に複数の新しい$dbhを作成すると、不快な問題が発生する可能性があります。 そんなことしないで。 (TBR)
Any child statement handles are effectively destroyed when take_imp_data() is called.
子文ハンドルは、take_imp_data() が呼び出されると正しく破壊されます。
The take_imp_data method was added in DBI 1.36 but wasn't useful till 1.49.
take_imp_data メソッドは DBI 1.36 で追加されましたが 1.49 までは有用ではありませんでした。
データベースハンドル属性¶
This section describes attributes specific to database handles.
このセクションではデータベースハンドルに特有の属性について記述します。
Changes to these database handle attributes do not affect any other existing or future database handles.
これらのデータベースハンドル属性を変更しても、既存の他の データベースハンドルあるいはこの後、生成されるデータベースハンドルには 影響を与えません。
Attempting to set or get the value of an unknown attribute generates a warning, except for private driver-specific attributes (which all have names starting with a lowercase letter).
ドライバ特有のプライベートな属性(これらの名前は小文字ではじまります)を 除いては、決められていない属性を設定あるいは取得しようとすると 警告が発生します。
Example:
例:
$h->{AutoCommit} = ...; # set/write
... = $h->{AutoCommit}; # get/read
AutoCommit (boolean)¶
If true, then database changes cannot be rolled-back (undone). If false, then database changes automatically occur within a "transaction", which must either be committed or rolled back using the commit or rollback methods.
真であれば、データベースの変更をロールバックする(元に戻す)ことは できません。 偽であれば、データベースの変更は自動的に「トランザクション」の中に入り、 commit または rollback メソッドを使ってコミットあるいは ロールバックされなければなりません。
Drivers should always default to AutoCommit mode (an unfortunate choice largely forced on the DBI by ODBC and JDBC conventions.)
ドライバはデフォルトを AutoCommit モードにしなければいけません (ODBC と JDBC の決まりにより、残念ながら DBI はこうせざるを得ません。)
Attempting to set AutoCommit to an unsupported value is a fatal error. This is an important feature of the DBI. Applications that need full transaction behaviour can set $dbh->{AutoCommit} = 0 (or set AutoCommit to 0 via "connect") without having to check that the value was assigned successfully.
AutoCommit をサポートされていない値に設定しようとすると、致命的な エラーになります。 これは DBI の重要な機能です。 完全なトランザクションを必要とするアプリケーションは、値が正しく代入されたか どうかをチェックすることなく $dbh->{AutoCommit} = 0 と する(または "connect" メソッドでの AutoCommit を 0 に設定する)ことが できます。
For the purposes of this description, we can divide databases into three categories:
この点から、データベースを三つのカテゴリに分けることができます。
Databases which don't support transactions at all.
Databases in which a transaction is always active.
Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
全くトランザクションをサポートしていないデータベース
いつでもトランザクションが有効なデータベース
明示的にトランザクションを開始(C<'BEGIN WORK'>などにより)しなければいけないデータベース
* Databases which don't support transactions at all
* 全くトランザクションをサポートしていないデータベース
For these databases, attempting to turn AutoCommit off is a fatal error. commit and rollback both issue warnings about being ineffective while AutoCommit is in effect.
これらのデータベースで、AutoCommit をオフにしようとすると 致命的エラーになります。 commit, rollback は AutoCommit が有効な間は無効であるという 警告を起こします。
* Databases in which a transaction is always active
* いつでもトランザクションが有効なデータベース
These are typically mainstream commercial relational databases with "ANSI standard" transaction behaviour. If AutoCommit is off, then changes to the database won't have any lasting effect unless "commit" is called (but see also "disconnect"). If "rollback" is called then any changes since the last commit are undone.
「ANSI標準」トランザクション機能を持った商用リレーショナルデータベースでは、 これが主流です。 AutoCommit がオフであると、データベースへの変更は "commit" されるまで 有効になりません (しかし "disconnect" もご覧ください)。 もし "rollback" が呼ばれると、最後のコミット以降のいかなる変更も元に 戻されます。
If AutoCommit is on, then the effect is the same as if the DBI called commit automatically after every successful database operation. So calling commit or rollback explicitly while AutoCommit is on would be ineffective because the changes would have already been committed.
AutoCommit がオンであると、DBI はまるで正常終了したデータベース操作の後、 自動的に commit を呼んでいるのと同じように振る舞います。 従って AutoCommit がオンの間に commit, rollback を明示的に 呼び出しても、すでにコミットされてしまっているので、何も効果がありません。
Changing AutoCommit from off to on will trigger a "commit".
AutoCommit をオフからオンに変えると、大抵のドライバは "commit" します。
For databases which don't support a specific auto-commit mode, the driver has to commit each statement automatically using an explicit COMMIT after it completes successfully (and roll it back using an explicit ROLLBACK if it fails). The error information reported to the application will correspond to the statement which was executed, unless it succeeded and the commit or rollback failed.
自動コミットモードを特にサポートしていないデータベースでは、ドライバは 各文が正常終了したら、明示的に COMMIT することにより、 自動的にコミットしなければいけません(失敗したら明示的に ROLLBACK して 元に戻さなければいけません)。 アプリケーションに伝えられるエラー情報は、文が正常終了した後、 コミットやロールバックが失敗しない限りは、実行された文に 対応しなければいけません。
* Databases in which a transaction must be explicitly started
* トランザクションが明示的に開始されなければならないデータベース
For these databases, the intention is to have them act like databases in which a transaction is always active (as described above).
これらのデータベースでは、トランザクションは(上記のような)いつでも 有効になるデータベースと同じようにします。
To do this, the driver will automatically begin an explicit transaction when AutoCommit is turned off, or after a "commit" or "rollback" (or when the application issues the next database operation after one of those events).
こうするため、ドライバは AutoCommit がオフになるか、 "commit" や "rollback" の後(あるいはアプリケーションがこれらの イベントの一つの後次のデータベース操作を行ったとき)、自動的に トランザクションを開始します。
In this way, the application does not have to treat these databases as a special case.
こうして、アプリケーションはこれらのデータベースを特別なケースとして 扱わなくてもよくなるのです。
See "commit", "disconnect" and "Transactions" for other important notes about transactions.
トランザクションについてのほかの重要な情報については "commit", "disconnect", "Transactions" をご覧ください。
Driver (handle)¶
Holds the handle of the parent driver. The only recommended use for this is to find the name of the driver using:
ハンドルの親ドライバを保持します。 唯一推奨されるこれの使い方は以下のようにしてドライバの名前を 見つけることだけです:
$dbh->{Driver}->{Name}
Name (string)¶
Holds the "name" of the database. Usually (and recommended to be) the same as the "dbi:DriverName:..." string used to connect to the database, but with the leading "dbi:DriverName:" removed.
データベースの名前が入ります。 通常は(そして推奨されることですが)データベースへの接続に使われる "dbi:DriverName:..." 文字列から先頭の "dbi:DriverName:" を 取ったものになります。
Statement (string, read-only)¶
Returns the statement string passed to the most recent "prepare" method called in this database handle, even if that method failed. This is especially useful where RaiseError is enabled and the exception handler checks $@ and sees that a 'prepare' method call failed.
このデータベースハンドルで最後の "prepare" メソッドに渡された 文文字列を返します。 もしそのメソッドが失敗していたとしてもです。 これは RaiseError が有効になっていて、例外ハンドラが $@ をチェックし、 'prepare' メソッドが失敗したかもしれないと思われるときには特に便利でしょう。
RowCacheSize (integer)¶
A hint to the driver indicating the size of the local row cache that the application would like the driver to use for future SELECT statements. If a row cache is not implemented, then setting RowCacheSize is ignored and getting the value returns undef.
アプリケーションがドライバに後からの SELECT 文のために使わせたい ローカルな行キャッシュの大きさを示すドライバへのヒントです。 行キャッシュが実装されていなければ、RowCacheSize の設定は無視され、値は undef が返ります。
Some RowCacheSize values have special meaning, as follows:
RowCacheSize の値には以下のような意味があります:
0 - Automatically determine a reasonable cache size for each C<SELECT>
1 - Disable the local row cache
>1 - Cache this many rows
<0 - Cache as many rows that will fit into this much memory for each C<SELECT>.