更新: 只是想出了一個更好的方法。
假設您在database.php中2數據庫配置,一個是默認的,另一個是備份 即
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'temp_test1';
//.......
$db['backup']=$db['default'];
$db['backup']['hostname'] = 'localhost1';
$db['backup']['username'] = 'root';
$db['backup']['password'] = '';
$db['backup']['database'] = 'temp_test1';
現在,這增加了database.php中文件的末尾
//check to see if you can connect
[email protected]_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
if($conn) //check to see if it's connecting, if it is close this connection
{
mysql_close($conn);
}
else{ //if it isnt
$db['default']=$db['backup']; //replace the default credentials with the backup credentials
}
OLD POST: 您可以採取很多方法。
您可以檢查是否有特定的連接是通過這個mysql_ping(開放),即
$conn=mysql_connect(...);
if(mysql_ping($conn)){...};
,所以你可以用這種方法來決定選擇哪個數據庫。
對於codeigniter,一種方法(這是一個相當糟糕的我會說,但方法不會少),是混亂的系統文件。在DB_Driver,在代碼的這一部分:
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if (! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
是它嘗試連接,並且如果檢查連接是成功的,並且如果不給出錯誤。
我不知道你如何做CI的異常處理,但基本上你應該處理異常並連接到不同的數據庫。
因爲我不知道異常處理,說我創建一個database_backup.php文件的config文件夾主機名,用戶名,密碼和數據庫變量。然後我會更改代碼以這種
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if (! $this->conn_id) //oops, first connection failed
{
//no problem, change the credentials of the database to our backup credentials
$ci=&get_instance();
$ci->load->config('database_backup');
$this->username=$ci->config->item('username');
$this->password=$ci->config->item('password');
$this->database=$ci->config->item('database');
$this->hostname=$ci->config->item('hostname');
//try to connect to database once more
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource STILL?nothing we can do now, throw an error
if (! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
}
CI提供多個數據庫連接。 http://codeigniter.com/user_guide/database/connecting.html – GBD
我知道,但如何檢查主數據庫下降?並使用備用數據庫? – Shawon