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

标签 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 返回的数据完全不同,我似乎无法从当前连接中获取数据库名称。

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

最佳答案

我要同时连接 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; 
        }
    }
}

关于php - 如何使用 MySQL PDO 检测数据库名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9979535/

相关文章:

php - (Bigcommerce API) - 向现有产品添加图像

mysql - 在 MySQL 中使用删除、更新、插入

c# - 如何使用 C# 安全连接到 MySQL,反编译时不显示任何信息

c# - C# 查询三张表

mysql - sql多对多查询索引优化

PHP-FPM 错误日志显示 "Not a JPEG file: starts with 0x47 0x49"

php - 使用 PHPSpreadsheet 构建非常大的电子表格

mysql - 将标记从 XML 文件加载到 Google Map API

mysql - 从具有多个表的架构中查询

javascript - 使用数组制作折线图 - D3.js