在我们的项目中有时可能须要连接不止一个数据库。在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. 传智播客PHP面试题宝典开放下载

    上下卷面试题更新完毕,一部让菜鸟4k+入职的 面试题宝典 http://php.itcast.cn/news/20130806/11490333788.shtml php视频教程 下载 http:// ...

  2. 在IIS上部署基于django WEB框架的python网站应用

    django是一款基于python语言的WEB开源框架,本文给出了如何将基于django写的python网站部署到window的IIS上. 笔者的运行环境: Window xp sp3 IIS 5.1 ...

  3. .Net中的插件框架Managed Extensibility Framework

    Managed Extensibility Framework(MEF)是微软的一个用来扩展.NET应用程序的框架,它最初为了满足Visual Studio里的编辑器的需求,比如说,延迟加载所有东西和 ...

  4. ARM JTAG 20

    http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0499b/BEHEIHCE.html he ARM JTAG 20 co ...

  5. datagrid在MVC中的运用02-结合搜索

    本文接着上一篇,来体验给datagrid加上搜索功能.主要涉及到: ※ 把一个div与datagrid相关起来 ※ datagrid接收查询参数 ※ 查询参数的封装 效果图: 查询参数封装 分页相关的 ...

  6. MVC三级联动无刷新

    本篇实现有关客户.订单和产品的无刷新三级联动,先看最终效果: 没有选择时,后2个Select状态为禁用: 当选择第1个Select,第2个Select可供选择,第3个Select依旧禁用: 当选择第2 ...

  7. spring boot集成RabbitMQ

    原文:https://www.jianshu.com/p/e1258c004314 RabbitMQ作为AMQP的代表性产品,在项目中大量使用.结合现在主流的spring boot,极大简化了开发过程 ...

  8. jsp中简易版本的图片上传程序

    1.下载相应的组件的最新版本 Commons FileUpload 可以在http://jakarta.apache.org/commons/fileupload/下载 附加的Commons IO   ...

  9. Spring事务处理探究

    开发环境: OS:windows XP       Web Server: jakarta-tomcat-5.0.28       DataBase Server: MS SQL Server 200 ...

  10. Ip和long互转

    // <summary> /// 将127.0.0.1形式的IP地址转换成十进制整数 /// </summary> /// <param name="strIp ...