2011-12-28 35 views
0

我已經創建了一個類方法,用於動態創建數據源以檢查給定的數據庫連接信息是否正確。持有該信息用於連接的陣列是以下形式:CakePHP動態創建數據源創建錯誤

Array 
(
    [datasource] => Database/Mysql 
    [persistent] => 0 
    [host] => localhost 
    [login] => root 
    [password] => 
    [database] => wp33 
    [prefix] => dr_ 
    [encoding] => UTF8 
    [port] => 
) 

,我的方法的代碼在它:

@App::import('Model', 'ConnectionManager'); 

ConnectionManager::create('Default', $config); 
$db = ConnectionManager::getDataSource('default'); 

if(!$db->isConnected()) 
{ 
    $this->Session->setFlash(__d('dir', 'Could not connect to database.'), 'Flash/error'); 
    return; 
} 

注意$配置從上面的數組保存數據。

的問題是,該方法的代碼返回該錯誤:

丟失的數據庫連接 錯誤:SQLSTATE [42000] [1049]未知數據庫「wp33」需要一個數據庫連接 錯誤:請確認您所創建的文件:app \ Config \ database.php。

因爲數據庫shema wp33在我的數據庫服務器中不存在。

我喜歡做的是停止CakePHP端的錯誤,並用$ this-> Session-> setFlash向我的客戶端顯示一個錯誤,而不是默認的CakePHP錯誤。

有什麼好主意嗎?

回答

1

捕獲MissingDatabaseException並使用getMessage()將錯誤消息設置爲會話閃存。

try { 
    ConnectionManager::create('Default', $config); 
    $db = ConnectionManager::getDataSource('default'); 
} catch (MissingDatabaseException $e) { 
    $this->Session->setFlash($e->getMessage()); 
} 

就像這樣。