简体   繁体   中英

If database connection fails, connect to another database

Is there a possability to do so? My intention is the following: I want spring/hibernate to conntect to a specific database but when the conntection fails I want it to connect to my localhost db.

The connection to my db is established by a datasource located in my spring app-context.

Thanks for your answers!

Sure. Just use a secondary connection..

include('../includes/connection.php');

$mysqli= new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);

    if($mysqli->connect_errno > 0){
        die('Unable to connect to database [' . $db->connect_error . ']');
//Add another string in here.
include('../includes/otherconnection.php');

$mysqli= new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if($mysqli->connect_errno > 0){
        die('Unable to connect to database also [' . $db->connect_error . ']');
}

    }

Of course, if that second one fails, you're still beat. But that's one way to handle it.

I was too lazy to do it right, so here is what I did:

I created a second datasource and just comment one out, if I don't need it. That's it. Everything else seems to be a bit complicated to me.

Well, if you don't need this intelligence "on the fly" (since you are commenting one out), you could create profiles in Maven and define your datasource configurations in there.

Create an application.properties, containing your database information properties. The values are going to be provided by a Maven profile (and it's filtered resources). Once you build your application, Spring should read these properties ( PropertyPlaceholderConfigurer in an option) and create your datasource properly.

It's "cleaner" and really not that hard to implement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM