ci同时使用多数据库

  • A+
所属分类:CI

(1)首先在application/config/database.php中添加数据库信息

$active_group = 'default';  //这里指明默认的db

$db['default'] = array(
		'dsn'	=> '',
		'hostname' => '1.1.1.1',
		'username' => 'XXXXXX',
		'password' => 'XXXXX',
		'database' => 'db1',
		'dbdriver' => 'mysqli',
		'dbprefix' => '',
		'pconnect' => FALSE,
		'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
);


$db['another_db'] = array(
		'dsn'	=> '',
		'hostname' => '1.1.1.2',
		'username' => '*******',
		'password' => '*******',
		'database' => 'db2',
		'dbdriver' => 'mysqli',
		'dbprefix' => '',
		'pconnect' => FALSE,
		'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
);

(2)想使用指定的db,为其创建一独立的model

代码如下:

<?php
class Another_model extends CI_Model{
        //定义一个数据库变量,并在构造函数中,为该变量赋值为 目标数据库信息
	private $db;

	function Another_model()
	{
                //在构造函数中,指定该model使用的数据库.
		$this->db = $this->load->database('another_db', true);
	}

        //其他php代码正常使用
        ...
        ...



  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: