Asf_Db::init

Connect databases used PDO drivers

从请求开始到结束期间, 以连接DB的配置信息作为单例模式条件

相同的配置, 第二次连接DB时, 会命中单例缓存, 框架会自动Check alive, 如果收到异常, 则重连DB一次

在CLI模式下, 不用去考虑DB资源断开的问题, 框架会自动重连DB

脚本执行结束, 框架会自动关闭所有的DB连接资源

异常信息比如: MySQL server has gone away


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));

Example #5 先连接DB, 基于本次会话的事务操作

<?php
use Asf\Db;

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

Db::init($configs);

try {
    Db::beginTransaction();
    $data = Db::update(array('status' => 3), array('id' => 123));
    Db::commit();
} catch (PDOException $e) {
    Db::rollBack();
}