开发者

Opening and Closing Multiple Database Connections with PDO in PHP

I'm working on simple database connection class. I'm using PHP and PDO.

As I would need to connect to multiple databases, I want to pool all the database connections in a class variable, and then access each as my scripts require.

Here is some pseudo code:

class Database_Driver
{
    private static $db_connect_pool;

    public static function openConnect($params_arr)
    {   
        try 
        {
            $db_driver_str = $开发者_JAVA百科params_arr['driver'];
            $db_host_str = $params_arr['host'];
            $db_name_str = $params_arr['db_name'];
            $db_username_str = $params_arr['db_username'];
            $db_password_str = $params_arr['db_password'];

            $connect_options_arr = array(PDO::ATTR_PERSISTENT => true);

            self::$db_connect_pool[''.$db_driver_str.'_'.$db_name_str.''] = new PDO("".$db_driver_str.":host=".$db_host_str.";db_name=".$db_name_str."", $db_username_str, $db_password_str, $connect_options_arr);                
        }        
        catch (Exception $e) 
        {
            print_r($e);
        }
    }

    public static getConnection($db_driver, $db_name)
    {
        return self::$db_connect_pool[''.$db_driver.''.$db_name.''];
    }
}

Database_Driver::openConnect($params_str);
$db_handle = Database_Driver::getConnection($db_driver, $db_name);
$st_handle = $db_handle->prepare('SQL Statement');
$st_handle->execute();

So at the end of my script I want to close all the open database connections. How can I do this? Do I just nullify the array i.e. self::$db_connect_pool = NULL; or is there some other way to do this effectively.

Thanks in advance.


As per the manual:

To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

So, unless want/need to clean up along the way to free up resources, you can leave the connections to close themselves.

Persistent connections are not closed at the end of the script, but are cached for future use. Setting such connections to NULL should close them.


PHP closes all open connections at the end of a script automatically, so what you're wanting to do should already be done.

If you need the connections closed prior to the end of script execution, however, you'll need to loop your connection pool array and close the connections individually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜