在Codeigniter中连接两个数据库

时间:2015-09-01 12:16:31

标签: php mysql database oracle codeigniter

我在codeigniter中连接两个数据库。我的database.php配置如下。

    $db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'dvrs',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

$db['orcl_db'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'mvrs',
    'password' => 'mvrs',
    'database' => 'MVRS',
    'dbdriver' => 'oci8',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

现在我正在自动加载默认数据库,并使用

按需将orcl_db加载到相应的模型中
$this->orclDB = $this->database->load("orcl_db", TRUE);

我正在连接dbs并成功运行查询。

我需要确保oracle服务器在连接之前可用,如果服务器不可用/没有响应,则显示正确的错误消息。

最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

以下是确保它的代码。

$this->orclDB = $this->load->database('orcl_db', TRUE);

        if (!$this->orclDB ->initialize()) {
            $response["status"] = false;
            $response["message"] = "Oracle DB is not available.";
        }

答案 1 :(得分:0)

为了关闭db调试,在db连接失败时抛出致命错误,请在数据库配置文件中使用$db['orcl_db']['db_debug'] = FALSE;。然后你可以检查数据库是否像这样加载:

if ( $this->load->database('orcl_db') === FALSE )
{
   // do whatever you think is appropriate, but do not panick
}