Asf_Db::init

Connect databases used PDO drivers

从请求开始到结束期间, 会缓存同一个DB连接资源,命中缓存时会先Check alive


Description

public static boolean function init(array $configs [, int $adapter_id = 0 [, bool $reset = false]])

Parameters

configs

连接数据库所需配置信息

adapter_id

MySQL(default): ASF\DB\MYSQL , SQLite: ASF\DB\SQLITE , PGSQL: ASF\DB\PGSQL

reset

0 单例连接数据库(default), 1 强制重新连接数据库, 不受单例限制

Return Values

成功时返回 TRUE , 失败时返回 FALSE / PDOException

Examples

Example #1 短连接单例模式连接MySQL数据库

<?php
use Asf\Db;

$configs = array(
    'dsn' => array('host' => '127.0.0.1', 'dbname' => 'test', 'port' => 6666),
    'username' => 'test',
    'password' => 'AbcdefRDvgedf',
);

var_dump(Db::init($configs));
var_dump(Db::init($configs));
var_dump(Db::init($configs));

Example #2 每次重新连接MySQL数据库 adapter_id = 0, reset = 1

<?php
$configs = array(
    'dsn' => array('host' => '127.0.0.1', 'dbname' => 'test', 'port' => 6666),
    'username' => 'test',
    'password' => 'AbcdefRDvgedf',
);

var_dump(Asf\Db::init($configs, 0, 1));

Example #3 设置MySQL数据库连接方式为长连接, PDO::ATTR_PERSISTENT = 1

<?php
$configs = array(
    'dsn' => array('host' => '127.0.0.1', 'dbname' => 'test', 'port' => 6666),
    'username' => 'test',
    'password' => 'AbcdefRDvgedf',
    'options' =>  array(
        PDO::ATTR_PERSISTENT => 1
    )
);

var_dump(Asf\Db::init($configs));

Example #4 设置MySQL数据库连接时间 2s, PDO::ATTR_TIMEOUT = 2

<?php
$configs = array(
    'dsn' => array('host' => '127.0.0.1', 'dbname' => 'test', 'port' => 6666),
    'username' => 'test',
    'password' => 'AbcdefRDvgedf',
    'options' =>  array(
        PDO::ATTR_TIMEOUT => 2
    )
);

var_dump(Asf\Db::init($configs));