如何在mysql数据库连接中使用try / catch异常

时间:2016-06-06 23:19:44

标签: php mysql database oop mysql-connect

我需要连接数据库,不需要显示错误。我必须使用try / catch异常。

 class MySqlDatabase {
private  $connection;

function __construct() {
    $this->open_connection();
}
public function open_connection() {
    $this->connection = mysql_connect(HOST_NAME, DB_USER, DB_PASSWORD);
    if (!$this->connection) {
        die('Not connected: ' . mysql_error());
    } else { 
        $db_selected = mysql_select_db(DB_NAME, $this->connection);
        if (!$db_selected) {
            die ('Can\'t use foo : ' . mysql_error());
        }
    }
}

public function getConnection() {
    return $this->connection;
}

}

1 个答案:

答案 0 :(得分:0)

为什么不使用 PDO

class MySqlDatabase 
{
    private  $connection;

    public function __construct() 
    {
       $this->open_connection();
    }

    public function open_connection() 
    {
        try {
            $this->connection = new PDO(
                sprintf('mysql:host=%s;dbname=%s;',
                HOST_NAME,DB_NAME),
                DB_USER,
                DB_PASSWORD,
                array(
                   PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
            ));
            $this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (PDOException $e) {

            printf('Connected problem, code: %s, meassage: %s',$e->getCode(),$e->getMessage());
            exit(1);
        }

    }

    public function getConnection() 
    {
        return $this->connection;
    }
}