codeigniter 怎么切换数据库

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了codeigniter 怎么切换数据库相关的知识,希望对你有一定的参考价值。

在开发中遇到一个问题:在一个应用中我需要用到两个库,不是主从,就比如user库和news库吧

如果是php的话是这样的逻辑:

mysql_connect();
mysql_select_db('user');
query.......
mysql_select_db('news');
query.....
mysql_close();

如果是ci的话就是配置两组数据库配置,然后
$this->load->database('user', TRUE);
query........
$this->load->database('news', TRUE);
query.....
参考技术A $DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);
这样就可以连两个库吧
如果你的两个是在同一台服务器上,只要数据库名字不一样就可以的,
$this->DB1;
$this->DB2;

在 codeigniter 中切换数据库服务器以进行读写操作。

【中文标题】在 codeigniter 中切换数据库服务器以进行读写操作。【英文标题】:Switch database server in codigniter for Read and Write Operations. 【发布时间】:2017-08-29 09:25:44 【问题描述】:

我已经为我的数据库服务器完成了主从设置,所以在我的 codigniter 应用程序中,我想要的是在主服务器上执行所有写入选项并在从服务器上执行所有读取操作。

谁能告诉我如何在 codigniter version3 中实现这一点。

谢谢。

【问题讨论】:

你可以有两个数据库连接,每当有写入操作时使用主对象,每当读取时使用salve obj 你在找这个吗?? ***.com/questions/8268853/… 实际上我的应用程序已经完成,我不想创建 2 个单独的连接,也不想编辑所有应用程序模型文件。所以我正在寻找 codigniter hack,它可以动态切换数据库以进行读写操作 您可以尝试使用系统数据库文件夹中存在的系统文件 我已经发布了答案,它正在按要求工作。 【参考方案1】:

你必须更新系统/数据库/DB_Driver.php 文件。

您只需在此文件中进行 3 处小更改,这非常简单。

1) 在 Construction 内部添加您的读写服务器凭据。

        $this->server_details['local_server']['hostname'] = "localhost";
        $this->server_details['local_server']['username'] = "select_user";
        $this->server_details['local_server']['password'] = "password";       

        $this->server_details['live_server']['hostname'] = "192.192.223.22";  
        $this->server_details['live_server']['username'] = "write_user"; 
        $this->server_details['live_server']['password'] = "password";        

2) Create New 函数将切换数据库连接以进行 select 和 write 查询。

 private function ebrandz_switch_db_for_read_write($sql)                

       if( $this->hostname == $this->server_details['local_server']['hostname'] &&  $this->username == $this->server_details['local_server']['username'] &&  $this->password == $this->server_details['local_server']['password'] )     
                   //echo $sql.'<br/>';
         if(stristr($sql, 'SELECT'))    
                            foreach($this->server_details['local_server'] as $index_key => $index_value )  
                                $this->$index_key = $index_value;  
                                         

                              $this->conn_id = null;  //unset resource link 
                              $this->initialize();   //Reinitialize connnection with new parameters                                                                                                       

                     else     
                            //die('write operation is not allowed.');
                            foreach($this->server_details['live_server'] as $index_key => $index_value )  
                                 $this->$index_key = $index_value;  
                              
                            $this->conn_id = null ; //unset resource link 
                            $this->initialize();    //Reinitialize connnection with new parameters                                                           
                    

                else if( $this->hostname == $this->server_details['live_server']['hostname'] &&  $this->username == $this->server_details['live_server']['username']  &&  $this->password ==  $this->server_details['live_server']['password'] )   

                    if(stristr($sql, 'SELECT'))  
                            foreach($this->server_details['local_server'] as $index_key => $index_value )  
                                 $this->$index_key = $index_value;  
                              

                            $this->conn_id = null ;  //unset resource link 
                            $this->initialize();     //Reinitialize connnection with new parameters      

                     else   
                            //die('write operation is not allowed.');
                            foreach($this->server_details['live_server'] as $index_key => $index_value )  
                                 $this->$index_key = $index_value;
                             

                            $this->conn_id = null ; //unset resource link 
                            $this->initialize();    //Reinitialize connnection with new parameters                                                           
                    

               

               //Code to re initialize the connection 
    

3) 在这个文件的查询函数中,你必须调用之前定义的函数。

// Verify table prefix and replace if necessary
    if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
    
        $sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
    

     /**
     * @author Anant Waykar
     * if query is read only then load some other database
     */
            $this->ebrandz_switch_db_for_read_write($sql);                     
      //Code to re initialize the connection 

【讨论】:

【参考方案2】:

你应该在`application/config/database.php'中提供第二个数据库信息

通常,您会设置默认数据库组,如下所示:

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

请注意,登录信息和设置在名为 $db['default'] 的数组中提供。

然后您可以在新数组中添加另一个数据库 - 我们称之为“otherdb”。

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

如果您需要同时连接多个数据库,您可以这样做:

$readDB = $this->load->database('otherdb', TRUE);

//For read:
$query = $readDB->select('first_name, last_name')->get('person');
var_dump($query);

//For write:
$this->db->insert('tablename', $insert_array);

【讨论】:

我知道我的要求是保持数据库连接处于活动状态并根据选择或更新查询切换服务器 意味着您希望根据选择或更新查询更改切换服务器,而不是扩展数据库库。 是的,实际上我的应用程序已经在运行并且有很多模型文件,所以我不想更新每个文件 我查过了,我认为不可能。但是您必须更改系统文件。如果你解决了,请告诉我。 是的,我知道我必须更改系统文件?

以上是关于codeigniter 怎么切换数据库的主要内容,如果未能解决你的问题,请参考以下文章

在 codeigniter 中切换数据库服务器以进行读写操作。

从数据库Codeigniter获取Lang

Codeigniter:如何使用数据库和用户会话数据构建多语言网站?

spring mybatis 多数据源之间怎么切换

多个mongoDB数据源,怎么配置动态切换

Redis切换为AOF不丢数据的正确步骤