目录
[TOC]
WorkerA 实现了 mysql、postgresql、sqlite 的数据库驱动,你可以在配置文件中进行数据库连接的配置。
## 配置连接
你可以在配置文件 config/database.php 中配置数据库连接,每个连接为 ”连接名 => 连接配置数组“ 的格式。你可以同时配置多个数据库连接,它们会在框架启动时被注册到单例。
注:由于多进程常驻内存的特性,单例的数据库连接比起传统的 apache、nginx 模型即节省了连接数,也提升了访问速度。
各个数据库的配置样例,config/database.php:
```php
...
'db_con' => [
// 配置 mysql
'con1' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'user' => 'username',
'password' => 'password',
'dbname' => 'database',
'charset' => 'utf8',
'prefix' => '',
'timezone' => '+8:00',
'collection' => 'utf8_general_ci',
// 'strict' => false,
// 'unix_socket' => '/var/run/mysqld/mysqld.sock',
// 'options' => [],
],
// 配置 postgresql
'con2' => [
'driver' => 'pgsql',
'host' => 'localhost',
'port' => '5432',
'user' => 'username',
'password' => 'password',
'dbname' => 'database',
'charset' => 'utf8',
'timezone' => '+8:00',
'prefix' => '',
// 'schema' => '',
// 'application_name' => '',
// 'sslmode' => 'disable',
// 'options' => [],
],
// 配置 sqlite
'con3' => [
'driver' => 'sqlite',
'dbname' => 'database.db',
'prefix' => '',
// 'options' => [],
],
],
...
```
## 获取连接
你可以使用 WorkerF\DB\DB 类的 connection($con_name) 方法获取连接。
```php
namespace App\Controller;
use App\Controller\Controller;
use WorkerF\DB\DB;
class TestController extends Controller
{
public function test()
{
$con = DB::connection('con1');
return $con->get();
}
}
```
