在现实世界的 CodeIgniter 项目中,开发人员需要同时使用多个数据库。这对开发人员提出了独特的挑战。由于这是一个很常见的问题,CodeIgniter 提供了一个简单的解决方案。
为了在您的 CodeIgniter 项目中使用多个数据库连接,您只需要创建多个配置数组来简化使用多个数据库。
默认配置数组
以下是默认 Codeigniter 数据库配置数组的结构:
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'mydefaultdatabase';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['autoinit'] = FALSE;
$db['default']['stricton'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
所以为了创建另一个数据库连接,你应该创建另一个配置数组。该数组必须遵循相同的结构。下面是数组的一个例子:
$db['anotherdb']['hostname'] = 'XXX.XXX.X.XXX';
$db['anotherdb']['username'] = 'another_user';
$db['anotherdb']['password'] = '';
$db['anotherdb']['database'] = 'anotherdatabase';
$db['anotherdb']['dbdriver'] = 'mysql';
$db['anotherdb']['dbprefix'] = '';
$db['anotherdb']['pconnect'] = TRUE;
$db['anotherdb']['db_debug'] = FALSE;
$db['anotherdb']['cache_on'] = FALSE;
$db['anotherdb']['cachedir'] = '';
$db['anotherdb']['char_set'] = 'utf8';
$db['anotherdb']['dbcollat'] = 'utf8_general_ci';
$db['anotherdb']['swap_pre'] = '';
$db['anotherdb']['autoinit'] = FALSE;
$db['anotherdb']['stricton'] = FALSE;
连接到正确的数据库
此时,您的示例项目中有两个数据库。要连接到特定数据库,您必须指定数据库名称。下面是正确的语法:
this->load->database(anotherdb, TRUE)
连接数据库后,可以进行数据库操作,如下图:
加载“另一个数据库”
$this->legacy_db = $this->load->database(anotherdatabase, true);
从“mydefaultdatabase”获取结果
$this->legacy_db->select ('*');
$this->legacy_db->from ('mydefaultdatabase');
$query = $this->legacy_db->get();
$result = $query->result ();
现在,如果您需要使用第二个数据库,则必须将连接发送到可在 model 函数中使用的变量:
function db_calling_model_method()
{
$otherdb = $this->load->database('anotherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.
$query = $otherdb->select('column_one, column_two')->get('table');
var_dump($query);
}
关闭连接
CodeIgniter 在确定代码不再需要连接后会关闭数据库连接。但是,作为一种良好做法,开发人员应明确关闭连接。以下是解决此问题的方法:
$this->db->close(); // for default Connection
$this->legacy_db->close(); //