在我们的项目中有时可能须要连接不止一个数据库。在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/地址。浏览器输出例如以下截图所看到的:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

能够看到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/地址。输出结果例如以下截图所看到的:

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

  1. Yii连接多个数据库的方法

    一.配置多数据库 大多数情况下,我们都会采用同一类型的数据库,只是为了缓解压力分成主从或分布式形式而已.声明你可以在 主配置文件 ( main.php )   中里声明其它的数据库连接: <?p ...

  2. 详解连接SQL Server数据库的方法,并使用Statement接口实现对数据库的增删改操作

    总结一下,连接SQL Server数据库需要以下几个步骤: 1. 导入驱动Jar包:sqljdbc.jar 2. 加载并注册驱动程序 3. 设置连接路径 4. 加载并注册驱动 5. 连接数据库 6. ...

  3. Unity 3D游戏开发学习路线(方法篇)

    Unity 3D本来是由德国的一些苹果粉丝开发的一款游戏引擎,一直只能用于Mac平台,所以一直不被业外人士所知晓.但是后来也推出了2.5版,同时发布了PC版本,并将其发布方向拓展到手持移动设备.Uni ...

  4. 可遇不可求的Question之导入mysql中文乱码解决方法篇

    可遇不可求的Question之导入mysql中文乱码解决方法篇 先 set names utf8;然后 source c:\1.sql ?

  5. Java+Selenium3方法篇24-单选和多选按钮操作

    Java+Selenium3方法篇24-单选和多选按钮操作 本篇介绍 webdriver处理前端单选按钮的操作.单选按钮一般叫raido button,就像我们在电子版的单选答题过程一样,单选只能点击 ...

  6. Java Learning Path(四) 方法篇

    Java Learning Path(四) 方法篇 Java作为一门编程语言,最好的学习方法就是写代码.当你学习一个类以后,你就可以自己写个简单的例子程序来运行一下,看看有什么结果,然后再多调用几个类 ...

  7. .NET Core 获取数据库上下文实例的方法和配置连接字符串

    目录 .NET Core 获取数据库上下文实例的方法和配置连接字符串 ASP.NET Core 注入 .NET Core 注入 无签名上下文 OnConfigure 配置 有签名上下文构造函数和自己n ...

  8. delphi 连接各中数据库方法

    ---恢复内容开始--- 数据库连接字符串的拼写规则的决定条件: • 连接的数据库的类型:SQL Server,Oracle,MySQL,Acess,MogoDB,Visual FoxPro(dBAS ...

  9. plsql连接本地oracle数据库,而远程主机却无法连接,出现无监听程序的解决方法(转)

    原文转自:plsql连接本地oracle数据库,而远程主机却无法连接,出现无监听程序的解决方法 最近在使用plsql连接本地oracle数据库的时候,在同一网络环境中,出现了可以连接本地oracle, ...

随机推荐

  1. Mac使用自带的屏幕共享实现VNC连接KVM时需要输入密码的问题解决

    别试了,下载这个软件VNC-Viewer,苹果自带的那个不行!!! https://www.realvnc.com/en/connect/download/viewer/macos/

  2. 用 Apache 发布 ASP.NET 网站

    由于服务器需要发布 JSP .PHP.ASP.NET 几种网站进行测试,Apache 肯定是支持 JSP  和 PHP .鉴于 Apache 的开放精神 ,ASP.Net 应该也是支持的,于是乎 Go ...

  3. 如何在发型不乱的前提下应对单日十亿计Web请求

    原文地址:http://developer.51cto.com/art/201502/464640.htm 就在不久之前,AppLovin移动广告平台的单一广告请求数量突破了200亿大关——相当于每一 ...

  4. Android实例剖析笔记(四)

    摘要:分析NoteEditor这个类和以及Content Provider机制 NoteEditor深入分析 首先来弄清楚“日志编辑“的状态转换,通过上篇文章的方法来做下面这样一个实验,首先进入“日志 ...

  5. 解决小米手机不能运行Android Studio程序的问题

    转载自:解决小米手机不能运行Android Studio程序的问题 问题描述 Android Studio升级到2.3版本之后,小米手机MIUI8不能运行Android Studio程序,报如下错误: ...

  6. EJB实体Bean怎样和数据库中表关联?

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ejb-jar PUBLIC "- ...

  7. Selenium2+python自动化51-unittest简介

    前言 熟悉java的应该都清楚常见的单元测试框架Junit和TestNG,这个招聘的需求上也是经常见到的.python里面也有单元测试框架-unittest,相当于是一个python版的junit. ...

  8. JDBC连接oracle RAC数据库配置

    RAC的配置如下: node1:ip地址192.168.60.132,实例名:rac1,主机名:rac1 node2:ip地址192.168.60.144,实例名:rac2,主机名:rac2 RAC服 ...

  9. 似然和对数似然Likelihood & LogLikelihood

    One of the most fundamental concepts of modern statistics is that of likelihood. In each of the disc ...

  10. HTTP参数CONNETCTION_TIMEOUT和SO_TIMEOUT区别

    在开发中经常碰到这两个参数,但是之前对它们的真正含义一直比较模糊,今天通过调试程序并且结合官方文档,了解了两者的含义与区别. 参数的定义直接去看官方的文档(httpcore-4.3) org.apac ...