1. 程式人生 > >thinkphp——配置資料庫連線的三種方法

thinkphp——配置資料庫連線的三種方法

                           thinkphp——配置資料庫連線的三種方法

一 配置檔案database.php:

1 直接在應用目錄的database.php檔案裡配置(適用於所有模組)

2 在指定模組下的database.php檔案裡配置(適用於指定模組)

二 控制器裡動態配置

需要在控制器裡引入Db類:

use think\Db;

1 Db::connect([ 配置資訊]);

Db::connect([
    // 資料庫型別
    'type'        => 'mysql',
    // 資料庫連線DSN配置
    'dsn'         => '',
    // 伺服器地址
    'hostname'    => '127.0.0.1',
    // 資料庫名
    'database'    => 'thinkphp',
    // 資料庫使用者名稱
    'username'    => 'root',
    // 資料庫密碼
    'password'    => '',
    // 資料庫連線埠
    'hostport'    => '',
    // 資料庫連線引數
    'params'      => [],
    // 資料庫編碼預設採用utf8
    'charset'     => 'utf8',
    // 資料庫表字首
    'prefix'      => 'think_',
]);

 2 Db::connect(配置資訊);  使用字串方式

Db::connect('mysql://root:[email protected]:3306/thinkphp#utf8');

字串連線的定義格式為:

資料庫型別://使用者名稱:密碼@資料庫地址:資料庫埠/資料庫名#字符集 

3 Db::connect(配置檔案);

如果在應用配置檔案(注意這裡不是資料庫配置檔案)中配置了額外的資料庫連線資訊

//資料庫配置1
'db_config1' => [
    // 資料庫型別
    'type'        => 'mysql',
    // 伺服器地址
    'hostname'    => '127.0.0.1',
    // 資料庫名
    'database'    => 'thinkphp',
    // 資料庫使用者名稱
    'username'    => 'root',
    // 資料庫密碼
    'password'    => '',
    // 資料庫編碼預設採用utf8
    'charset'     => 'utf8',
    // 資料庫表字首
    'prefix'      => 'think_',
],
//資料庫配置2
'db_config2' => 'mysql://root:
[email protected]
:3306/thinkphp#utf8';

 使用這個配置連線:

Db::connect('db_config1');

 三 在模型裡配置

1 使用connection屬性

//在模型裡單獨設定資料庫連線資訊
namespace app\index\model;

use think\Model;

class User extends Model
{
    protected $connection = [
        // 資料庫型別
        'type'        => 'mysql',
        // 資料庫連線DSN配置
        'dsn'         => '',
        // 伺服器地址
        'hostname'    => '127.0.0.1',
        // 資料庫名
        'database'    => 'thinkphp',
        // 資料庫使用者名稱
        'username'    => 'root',
        // 資料庫密碼
        'password'    => '',
        // 資料庫連線埠
        'hostport'    => '',
        // 資料庫連線引數
        'params'      => [],
        // 資料庫編碼預設採用utf8
        'charset'     => 'utf8',
        // 資料庫表字首
        'prefix'      => 'think_',
    ];
}

 2 也可以採用DSN字串方式定義

//在模型裡單獨設定資料庫連線資訊
namespace app\index\model;

use think\Model;

class User extends Model
{
    //或者使用字串定義
    protected $connection = 'mysql://root:[email protected]:3306/thinkphp#utf8';
}

3 支援直接使用資料庫連線的配置名稱

//在模型裡單獨設定資料庫連線資訊
namespace app\index\model;

use think\Model;

class User extends Model
{
    // 直接使用配置引數名
    protected $connection = 'db_config1';
}