问题描述
我正在尝试检查Laravel中是否连接了数据库.
I am trying to check if a database is connected in Laravel.
我已经浏览了文档,找不到任何东西.我找到的最接近的东西是此,但这不能解决我的问题问题.
I've looked around the documentation and can't find anything. The closest thing I've found is this, but this doesn't solve my problem.
我有三个在不同机器上设置的MySQL实例.以下是我要实现的目标的简化版本.
I have three instances of MySQL that are set up on different machines. Below is a simplified version of what I am trying to achieve.
- 如果已连接数据库1,则将数据保存到其中
- 如果未连接数据库1,请检查数据库2是否已连接
- 如果已连接数据库2,则向其中保存数据
- 如果未连接数据库2,请检查是否已连接数据库3
- 如果已连接数据库3,则将数据保存到其中
需要明确的是,有没有一种方法可以检查在Laravel 5.1中是否已连接数据库?
To be clear, is there a way to check that a database is connected in Laravel 5.1?
推荐答案
尝试仅获取基础PDO实例.如果那个失败,则Laravel无法连接到数据库!
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
这篇关于Laravel 5.1-检查数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!