ci高级用法篇之连接多个数据库

在我们的项目中有时可能需要连接不止一个数据库,在ci中如何实现呢?

我们在本地新建了两个数据库,如下截图所示:

修改配置文件database.php文件为如下格式(读者根据自己数据库的情况修改相应参数的配置):

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
|	['dsn']      The full DSN string describe a connection to the database.
|	['hostname'] The hostname of your database server.
|	['username'] The username used to connect to the database
|	['password'] The password used to connect to the database
|	['database'] The name of the database you want to connect to
|	['dbdriver'] The database driver. e.g.: mysqli.
|			Currently supported:
|				 cubrid, ibase, mssql, mysql, mysqli, oci8,
|				 odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
|	['dbprefix'] You can add an optional prefix, which will be added
|				 to the table name when using the  Query Builder class
|	['pconnect'] TRUE/FALSE - Whether to use a persistent connection
|	['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
|	['cache_on'] TRUE/FALSE - Enables/disables query caching
|	['cachedir'] The path to the folder where cache files should be stored
|	['char_set'] The character set used in communicating with the database
|	['dbcollat'] The character collation used in communicating with the database
|				 NOTE: For MySQL and MySQLi databases, this setting is only used
| 				 as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
|				 (and in table creation queries made with DB Forge).
| 				 There is an incompatibility in PHP with mysql_real_escape_string() which
| 				 can make your site vulnerable to SQL injection if you are using a
| 				 multi-byte character set and are running versions lower than these.
| 				 Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
|	['swap_pre'] A default table prefix that should be swapped with the dbprefix
|	['encrypt']  Whether or not to use an encrypted connection.
|	['compress'] Whether or not to use client compression (MySQL only)
|	['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
|							- good for ensuring strict SQL while developing
|	['failover'] array - A array with 0 or more data for connections if the main should fail.
|	['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| 				NOTE: Disabling this will also effectively disable both
| 				$this->db->last_query() and profiling of DB queries.
| 				When you run a query, with this setting set to TRUE (default),
| 				CodeIgniter will store the SQL statement for debugging purposes.
| 				However, this may cause high memory usage, especially if you run
| 				a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active.  By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/

$active_group = 'test';//默认连接test数据库
$active_record = TRUE;//是否开启active record

$db['test'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'test',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => TRUE,
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);
//test2数据库相关配置
$db['test2'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'test2',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => TRUE,
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

在applicaton/model目录下创建两个文件:score.php

<?php
class Score extends CI_Model {

    private $tableName = 'score';

    function __construct()
    {
        parent::__construct();
    }

    public function getAllScores(){
        return $this->db->get($this->tableName);
    }
}

和students.php

<?php
class Students extends CI_Model {

    private $tableName = 'students';

    function __construct()
    {
        parent::__construct();
    }

    public function getAllStudents(){
        return $this->db->get($this->tableName);
    }
}

修改welcome控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends ci_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct(){
		parent::__construct();
		$this->load->model('students');
		$this->load->model('score');
	}

	public function index()
	{
		var_dump($this->students->getAllStudents()->result());
		var_dump($this->score->getAllScores()->result());
		die('测试结束');
	}
}

访问http://localhost/ci2/地址,浏览器输出如下截图所示:

可以看到ci没有找到score表,我们需要在score.php文件中用

$this->db = $this->load->database('test2', TRUE);

显示指明score所在的数据库:

<?php
class Score extends CI_Model {

    private $tableName = 'score';
    private $db;

    function __construct()
    {
        parent::__construct();
        $this->db = $this->load->database('test2', TRUE);
    }

    public function getAllScores(){
        return $this->db->get($this->tableName);
    }
}

再次访问访问http://localhost/ci2/地址,输出结果如下截图所示:

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-12-28 15:07:20

ci高级用法篇之连接多个数据库的相关文章

ci高级用法篇之扩展核心类

在上一篇文章ci高级用法篇之创建自己的类库中,你是否觉得每个控制器的构造方法都去执行校验代码其实违背了编程规范中的DRY(do'nt repeat yourself)原则呢? 其实我们完全可以把校验的代码在父类的构造函数中.ci中控制器的父类是CI_Controller,现在我们来扩展这个父类. 在application/core目录下创建一个类文件,MY_Controller.php,内容如下: <?php class MY_Controller extends ci_Controller{

sed和awk之sed篇(含sed高级用法)

(原创文章,谢绝转载~) sed(stream editor)和 awk 是linux环境下处理文本.数据的强大"利器",sed对数据列的处理稍逊,awk则更似一门语言,control flow的语法基本和c语言一样,能够处理复杂的逻辑,二者经常配合正则表达式使用.本文简述sed用法. sed对输入流(文本数据)逐行处理,其基本格式为: sed (OPTIONS...) [SCRIPT] [INPUTFILE...]#examplessed '10d' test.txtsed -i '

Mybatis最入门---ResultMaps高级用法(上)

[一步是咫尺,一步即天涯] 接上文,我们基本的单表查询使用上文中的方式已经能够达到目的.但是,我们日常的业务中也存在着多表关联查询,结果是复杂的数据集合等等.本文我们就来介绍ResultMaps的高级用法,本文,我们先介绍基本的概念,具体用法实例在下一篇中专门演示给大家.敬请期待! ------------------------------------------------------------------------------------------------------------

nmap命令-----高级用法

探测主机存活常用方式 (1)-sP :进行ping扫描 打印出对ping扫描做出响应的主机,不做进一步测试(如端口扫描或者操作系统探测): 下面去扫描10.0.3.0/24这个网段的的主机 1 nmap -sP 10.0.3.0/24 这个命令可以用于探测局域网有哪些机器 1 2 3 4 5 6 7 8 9 10 11 [[email protected] ~]# nmap -sP 10.0.3.0/24 Starting Nmap 5.51 ( http://nmap.org ) at 201

Newtonsoft.Json高级用法

手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数据,经过分析一个简单的列表接口每一行数据返回了16个字段,但是手机APP端只用到了其中7个字段,剩余9个字段的数据全部都是多余的,如果接口返回数据为40K大小,也就是说大约20K的数据为无效数据,3G网络下20K下载差不多需要1s,不返回无效数据至少可以节约1s的时间,大大提高用户体验.本篇将为大家

Git log高级用法

格式化Log输出 首先,这篇文章会展示几种git log格式化输出的例子.大多数例子只是通过标记向git log请求或多或少的信息. 如果你不喜欢默认的git log格式,你可以用git config的别名功能来给你想要的格式创建一个快捷方式. Oneline --oneline标记把每一个提交压缩到了一行中.它默认只显示提交ID和提交信息的第一行.git log --oneline的输出一般是这样的: 0e25143 Merge branch 'feature' ad8621a Fix a b

#define的高级用法

=========================================================== define中的三个特殊符号:#,##,#@ =========================================================== #define Conn(x,y) x##y #define ToChar(x) #@x #define ToString(x) #x (1)x##y表示什么?表示x连接y,举例说: int n = Conn(12

git log 高级用法

转自:https://github.com/geeeeeeeeek/git-recipes/wiki/5.3-Git-log%E9%AB%98%E7%BA%A7%E7%94%A8%E6%B3%95 内容很详细.实用. 这是一篇在原文(BY atlassian)基础上演绎的译文.除非另行注明,页面上所有内容采用知识共享-署名(CC BY 2.5 AU)协议共享. 每一个版本控制系统的出现都是为了让你记录代码的变化.你可以看到项目的历史记录--谁贡献了什么.bug是什么时候引入的,还可以撤回有问题的

再谈Newtonsoft.Json高级用法

上一篇Newtonsoft.Json高级用法发布以后收到挺多回复的,本篇将分享几点挺有用的知识点和最近项目中用到的一个新点进行说明,做为对上篇文章的补充. 阅读目录 动态改变属性序列化名称 枚举值序列化问题 全局设置 总结 回到顶部 动态改变属性序列化名称 "动态改变属性序列化名称"顾名思义:在不同场景下实体字段序列化后字段名称不同,比如有下面实体A,正常序列化后json为{"Id":"123"} public class A { public