MySQL Codeigniter - 多个数据库连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8268853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:49:28  来源:igfitidea点击:

Codeigniter - multiple database connections

mysqldatabasecodeigniter

提问by S.Sid

I have to retrieve a MySQL database information from master database and then connect to that database, and fetch some records.

我必须从 master 数据库中检索 MySQL 数据库信息,然后连接到该数据库,并获取一些记录。

I mean that holding one database I want to load another database.

我的意思是持有一个数据库我想加载另一个数据库。

Is it possible with Codeigniter? Right now I'm using following lines of code in my model.

Codeigniter 可以吗?现在我在我的模型中使用以下代码行。

function connectDb($credential)
{

    $config['hostname'] = $credential['server'];
    $config['username'] = $credential['username'];
    $config['password'] = $credential['password'];
    $config['database'] = $credential['database'];
    $config['dbdriver'] = "mysql";
    $config['dbprefix'] = "";
    $config['pconnect'] = FALSE;
    $config['db_debug'] = TRUE;
    $config['cache_on'] = FALSE;
    $config['cachedir'] = "";
    $config['char_set'] = "utf8";
    $config['dbcollat'] = "utf8_general_ci";

    $DB2=$this->load->database($config);

    $DB2->db->select('first_name,last_name');
    $query = $DB2->db->get('person');
    print_r($query);

}

its not working is there any other way?

它不起作用还有其他方法吗?

回答by Repox

You should provide the second database information in `application/config/database.php′

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

Normally, you would set the defaultdatabase group, like so:

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

$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;

Notice that the login information and settings are provided in the array named $db['default'].

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

You can then add another database in a new array - let's call it 'otherdb'.

然后,您可以在新数组中添加另一个数据库 - 我们称之为“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;

Now, to actually use the second database, you have to send the connection to another variabel that you can use in your model:

现在,要实际使用第二个数据库,您必须将连接发送到您可以在模型中使用的另一个变量:

function my_model_method()
{
  $otherdb = $this->load->database('otherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.

  $query = $otherdb->select('first_name, last_name')->get('person');
  var_dump($query);
}

That should do it. The documentation for connecting to multiple databases can be found here: http://codeigniter.com/user_guide/database/connecting.html

那应该这样做。连接到多个数据库的文档可以在这里找到:http: //codeigniter.com/user_guide/database/connecting.html

回答by Simmoniz

The best way is to use different database groups. If you want to keep using the master database as usual ($this->db) just turn off persistent connexionconfiguration option to your secondary database(s). Only master database should work with persistent connexion :

最好的方法是使用不同的数据库组。如果您想像往常一样继续使用主数据库 ($this->db),只需关闭辅助数据库的持久连接配置选项。只有主数据库应该与持久连接一起使用:

Master database

主数据库

$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;

Secondary database (notice pconnect is set to false)

辅助数据库(注意 pconnect 设置为 false)

$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'] = FALSE;
$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;

Then you can use secondary databases as database objectswhile using master database as usual :

然后你可以像往常一样使用主数据库作为数据库对象使用辅助数据库:

// use master dataabse
$users = $this->db->get('users');

// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
$stuff = $otherdb->get('struff');
$otherdb->insert_batch('users', $users->result_array());

// keep using master database as usual, for example insert stuff from other database
$this->db->insert_batch('stuff', $stuff->result_array());

回答by Mani

It works fine for me...

这对我来说可以...

This is default database :

这是默认数据库:

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Add another database at the bottom of database.php file

在 database.php 文件底部添加另一个数据库

$db['second'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mysecond',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

In autoload.php config file

在 autoload.php 配置文件中

$autoload['libraries'] = array('database', 'email', 'session');

The default database is worked fine by autoload the database library but second database load and connect by using constructor in model and controller...

通过自动加载数据库库,默认数据库可以正常工作,但是通过在模型和控制器中使用构造函数加载和连接第二个数据库...

<?php
    class Seconddb_model extends CI_Model {
        function __construct(){
            parent::__construct();
            //load our second db and put in $db2
            $this->db2 = $this->load->database('second', TRUE);
        }

        public function getsecondUsers(){
            $query = $this->db2->get('members');
            return $query->result(); 
        }

    }
?>

回答by Rayiez

Use this.

用这个。

$dsn1 = 'mysql://user:password@localhost/db1';
$this->db1 = $this->load->database($dsn1, true);     

$dsn2 = 'mysql://user:password@localhost/db2';
$this->db2= $this->load->database($dsn2, true);     

$dsn3 = 'mysql://user:password@localhost/db3';
$this->db3= $this->load->database($dsn3, true);   

Usage

用法

$this->db1 ->insert('tablename', $insert_array);
$this->db2->insert('tablename', $insert_array);
$this->db3->insert('tablename', $insert_array);

回答by Quetzy Garcia

While looking at your code, the only thing I see wrong, is when you try to load the second database:

在查看您的代码时,我发现唯一错误的是当您尝试加载第二个数据库时:

$DB2=$this->load->database($config);

When you want to retrieve the database object, you have to pass TRUEin the second argument.

当您想要检索数据库对象时,您必须在第二个参数中传递TRUE

From the Codeigniter User Guide:

来自Codeigniter 用户指南

By setting the second parameter to TRUE (boolean) the function will return the database object.

通过将第二个参数设置为 TRUE(布尔值),该函数将返回数据库对象。

So, your code should instead be:

所以,你的代码应该是:

$DB2=$this->load->database($config, TRUE);

That will make it work.

这将使它起作用。

回答by Dhiraj Shrestha

If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

注意:将单词“group_one”和“group_two”更改为您要连接到的特定组名称(或者您可以传递如上所示的连接值)。

By setting the second parameter to TRUE (boolean) the function will return the database object.

通过将第二个参数设置为 TRUE(布尔值),该函数将返回数据库对象。

Visit https://www.codeigniter.com/userguide3/database/connecting.htmlfor further information.

访问https://www.codeigniter.com/userguide3/database/connecting.html了解更多信息。