1. 程式人生 > 程式設計 >thinkphp 框架資料庫切換實現方法分析

thinkphp 框架資料庫切換實現方法分析

本文例項講述了thinkphp 框架資料庫切換實現方法。分享給大家供大家參考,具體如下:

資料庫配置:

 //資料庫配置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:1234@localhost:3306/thinkphp#utf8';

//預設資料庫讀取資料
$test = Db::name("test")->select();
//第二個資料庫讀取資料
$test1=Db::connect("DB_Config_1")->name("test")->select();

application/config.php

$db1 = [ 
'type'=>'mysql','hostname'=>'127.0.0.1','database'=>'testA','username'=>'root','password'=>'123456','hostport'=>'3306','params'=>[],'charset'=>'utf8','prefix'=>'',$db2 = [ 
'type'=>'mysql',atabase'=>'testB',Db::connect('db1')->query('select * from user where age=25');

方法配置

我們可以在呼叫Db類的時候動態定義連線資訊,例如:

Db::connect([
  // 資料庫型別
  'type'    => 'mysql',// 資料庫連線DSN配置
  'dsn'     => '',// 資料庫連線埠
  'hostport'  => '',// 資料庫連線引數
  'params'   => [],]);

或者使用字串方式:

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

字串連線的定義格式為:

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

注意:字串方式可能無法定義某些引數,例如字首和連線引數。

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

//資料庫配置1
'db_config1' => [
  // 資料庫型別
  'type'    => 'mysql',//資料庫配置2
'db_config2' => 'mysql://root:1234@localhost:3306/thinkphp#utf8';

我們可以改成

Db::connect('db_config1');
Db::connect('db_config2');

thinkphp 框架資料庫切換實現方法分析

database.php是框架預設的資料庫配置,裡面寫資料庫1的資訊,新建了個database2.php是放置資料庫2的資訊。

建立完資料庫2之後,在config配置檔案裡,檔案最後引入資料庫2的配置資訊

$db_con2 = require_once ('database2.php'),'db_con2' => $db_con2,

程式碼中引用:

選擇資料庫1的時候,我是用模型查詢的直接寫SQL語句:

//模型查詢
$user = new User();
$result = $user->where('username',$data['username'])
        ->where('password',$data['password'])
        ->find();

或者

User::where('id','1')->find();
//普通結構查詢
Db::table('think_user')->where('id',1)->find();

查詢資料庫2的資訊時,呼叫普通查詢語句:

$list = Db::connect('db_con2')
->table('nrf_amf_reg_info')
->alias('r')
->join('nrf_amf_server s','r.Id = s.nrf_amf_reg_Id','LEFT')
->paginate();

或者

$list = Db::connect('db_con2')->name('nrf_disc_record')->paginate();

注:nrf_amf_reg_info和nrf_disc_record為表名

更多關於thinkPHP相關內容感興趣的讀者可檢視本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結》、《ThinkPHP常用方法總結》、《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術總結》。

希望本文所述對大家基於ThinkPHP框架的PHP程式設計有所幫助。