downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

トランザクションおよび自動コミット> <定義済み定数
[edit] Last updated: Fri, 25 May 2012

view this page in

接続、および接続の管理

PDO 基底クラスのインスタンスを作成することにより、接続が確立されます。 どのドライバを使用するのかにかかわらず、常に PDO クラスを指定します。 コンストラクタに渡す引数により、データソース (いわゆる DSN) の指定や (もしあれば、オプションで) ユーザー名およびパスワードの指定を行います。

例1 MySQL への接続

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=test'$user$pass);
?>

接続時になんらかのエラーが発生した場合、PDOException オブジェクトがスローされます。エラー処理を行いたい場合はこの例外を キャッチします。あるいはこれを無視して、 set_exception_handler() で設定した グローバル例外ハンドラに処理を任せることもできます。

例2 接続エラーの処理

<?php
try {
    
$dbh = new PDO('mysql:host=localhost;dbname=test'$user$pass);
    foreach(
$dbh->query('SELECT * from FOO') as $row) {
        
print_r($row);
    }
    
$dbh null;
} catch (
PDOException $e) {
    print 
"エラー!: " $e->getMessage() . "<br/>";
    die();
}
?>

警告

PDO コンストラクタからの例外をアプリケーション内でキャッチしない場合、 zend エンジンはスクリプトの実行を終了し、バックトレースを表示します。 このバックトレースを見れば、データベースへの接続の詳細がわかってしまいます。 その中にはユーザー名やパスワードも含まれます。 (catch 文を使用して) 明示的に例外をキャッチするか、 あるいは set_exception_handler() を使用して 暗黙的に例外をキャッチするようにしましょう。

データベースへの接続に成功すると、PDO クラスのインスタンスが スクリプトに返されます。この PDO オブジェクトが存在する間、 接続がアクティブであり続けます。接続を閉じるには、他から 参照されていないことを保障することでオブジェクトを破棄する 必要があります。それには、オブジェクトを保持している変数に対して NULL を代入します。 明示的にこれを行わなかった場合は、スクリプトの終了時に自動的に 接続が閉じられます。

例3 接続を閉じる

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=test'$user$pass);
// ここで接続を使用します


// 使用を終了したので、閉じます
$dbh null;
?>

データベースサーバーへの持続的な接続による恩恵をこうむる web アプリケーションは多いでしょう。持続的な接続は、スクリプトが 終了しても閉じられずにキャッシュされ、他のスクリプトが同じ内容の 接続を要求してきた際にそれが再利用されます。持続的接続の キャッシュにより、スクリプトがデータベースを使用するたびに 新しい接続を確立するオーバーヘッドを避けることができます。 それにより、結果として web アプリケーションを高速化できるように なります。

例4 持続的な接続

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=test'$user$pass, array(
    
PDO::ATTR_PERSISTENT => true
));
?>

注意:

持続的な接続を使用したい場合は、ドライバのオプションを表す配列に PDO::ATTR_PERSISTENT を設定して PDO のコンストラクタに渡す必要があります。この属性を PDO::setAttribute() を用いてインスタンス作成後に設定した場合は、 そのドライバは持続的な接続を使用しません。

注意:

PDO ODBC ドライバを使用しており、ODBC ライブラリが ODBC 接続プーリングをサポートしている場合 (unixODBC および Windows はこれをサポートしています。他にもあるかもしれません) は、 PDO の持続的接続を使用せずに ODBC の接続プーリングに 接続キャッシュ処理を任せることを推奨します。 ODBC の接続プールは、プロセス内で他のモジュールと共有されています。 PDO が接続をキャッシュしてしまうと、その接続は ODBC の 接続プールに返されなくなり、他のモジュールによって新たな接続が 作成されてしまうようになります。



add a note add a note User Contributed Notes 接続、および接続の管理
alvaro at demogracia dot com 01-Jul-2011 10:07
On connection errors, the PDO constructor seems to do two things no matter your PDO::ATTR_ERRMODE setting:

1. Trigger a warning
2. Throw a PDOException

If you set the PDO::ATTR_ERRMODE parameter, it will only take effect on further operations.
jak dot spalding at gmail dot com 10-Apr-2011 12:35
Just thought I'd add in and give an explanation as to why you need to use 127.0.0.1 if you have a different port number.

The mysql libraries will automatically use Unix sockets if the host of "localhost" is used. To force TCP/IP you need to set an IP address.
ekkart at ekkart dot de 14-Oct-2010 03:43
In order to set the encoding of the database connection, use the exec function:
<?php
try {
   
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   
$dbh->exec("SET CHARACTER SET utf8");
   
$dbh = null;
} catch (
PDOException $e) {
    print
"Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>
angela 06-Apr-2010 02:53
I spent hours today trying to get my portable wamp to update a database, using localhost:800 and port 3307 for mysql. For it to work I needed to adjust the connect() instruction as described:
$dsn = "mysql:host=127.0.0.1;port=3307;dbname=mydatabase";
neville at whitespacers dot com 16-Oct-2009 03:40
To avoid exposing your connection details should you fail to remember to catch any exception thrown by the PDO constructor you can use the following class to implicitly change the exception handler temporarily.

<?php

Class SafePDO extends PDO {
 
        public static function
exception_handler($exception) {
           
// Output the exception details
           
die('Uncaught exception: ', $exception->getMessage());
        }
 
        public function
__construct($dsn, $username='', $password='', $driver_options=array()) {

           
// Temporarily change the PHP exception handler while we . . .
           
set_exception_handler(array(__CLASS__, 'exception_handler'));

           
// . . . create a PDO object
           
parent::__construct($dsn, $username, $password, $driver_options);

           
// Change the exception handler back to whatever it was before
           
restore_exception_handler();
        }

}

// Connect to the database with defined constants
$dbh = new SafePDO(PDO_DSN, PDO_USER, PDO_PASSWORD);

?>
dan dot franklin at pearson dot com 17-Apr-2008 09:37
Note that you can specify a port number with "port=####", but this port number will be ignored if the host is localhost.  If you want to connect to a local port other than the default, use host=127.0.0.1 instead of localhost.

 
show source | credits | sitemap | contact | advertising | mirror sites