Question

We are using DriverManager::getConnection in our Silex application to retrieve the connection to our database server, along with a properly instantiated Configuration class.

I am in charge of going back in the code and properly handling connection errors to display a user-friendly error message if the connection is currently down, for example.

In my head, this seems simple enough. But I can't find any way available of asserting the connection is valid before actually sending a Query.

Here is an example of building the connection :

use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Query\QueryBuilder;

// ... //

public function __construct( $host, $username, $password, $db, $port )
{
    $this->configuration = new Configuration();
        $connectionParams = array(
        'dbname' => $db,
        'user' => $username,
        'password' => $password,
        'host' => $host,
        'port' => $port,
        'driver' => 'pdo_mysql'
    );
        $this->connection = DriverManager::getConnection( $connectionParams, $this->configuration );
}

And a method the would fail given no valid connections are available

public function executeQuery( QueryBuilder $queryBuilder )
{
    $query = $queryBuilder->getSql();

    $statement = $queryBuilder->execute( $query );

    return $statement;
}

I've mostly use mysqli for which you can simply do something like this, from the mysqli doc.

I am seeking for an equivalent with our current workflow and have been surprised I couldn't get any relevant information regarding DB connection error handling using DBAL anywhere around...

I believe that means I am looking for the wrong thing and hope I can be guided in the right direction as I have to implement that for tomorrow! I will continue my research and post follow ups if I find anything relevant!

Thank you.

Was it helpful?

Solution

If the database connection is no good or goes away, Doctrine will throw an exception of some sort (I don't recall what, and it may well vary between drivers).

So you're probably going to want to find the appropriate place to catch those exceptions and deal with them nicely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top