如何使用MySQL PDO检测数据库名称

时间:2012-04-02 15:50:37

标签: php mysql sql sql-server pdo

我是PDO图书馆的新手,所以我为自己缺乏经验而道歉。我正在编写一个使用PDO库来构建和执行查询并返回结果的类,无论它们是什么。

在类中,我检测是否存在与数据库的开放连接,如果它与正在配置的数据库相同,则使用此数据库。这很容易使用MsSQL库,因为PDO::getAttribute()函数返回'CurrentDatabase'和'SQLServerName',所以我可以应用这样的条件:

if(!empty($this->PDO)){
    // Get the current connection information
    $current_connection = $this->PDO->getAttribute(PDO::ATTR_SERVER_INFO);
    // Return if the connection is the same
    if($this->connection_parameters['hostname']==$current_connection['SQLServerName']&&$this->connection_parameters['database']==$current_connection['CurrentDatabase']){
        return;
    }
}

然而,当谈到MySQL时,从PDO::getAttribute返回的数据完全不同,我似乎无法从当前连接获取数据库名称。

是否有人知道使用PDO中的PHP库来获取当前连接的MySQL连接数据库的函数或方法?

3 个答案:

答案 0 :(得分:2)

我要连接到MySQL和MsSQL,你必须有2个连接。但是,在实时连接上更改数据库非常简单。

以下简单检查PDO实例是否已存在以及是否正在使用所需的数据库。如果是,则继续此连接,否则会更改数据库。

// Test if the PDO object already exists
if(!empty($this->PDO)){

    // If connection is the same then select the database
    if($this->connection_engine==$this->PDO->getAttribute(PDO::ATTR_DRIVER_NAME)){

        // Get the current database in use
        $database = $this->PDO->query("SELECT {$this->select_db_function}");
        $database = $database->fetchAll(PDO::FETCH_NUM);
        $database = $database[0][0];

        // If the current database matches the new database then return
        if($database==$this->connection_parameters['database']){
            return; 
        }
    }
}

答案 1 :(得分:1)

我认为没有必要寻找已打开的连接,尤其是在检查当前数据库时。

为什么不能只打开连接,为它选择数据库,然后在整个课程中一直使用这个连接 - 就像每个人一样?

答案 2 :(得分:-1)

请参阅MySQL手册页上有关“USE database

的评论