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/地址。浏览器输出例如以下截图所看到的:
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高级使用方法篇之连接多个数据库的更多相关文章
- Yii连接多个数据库的方法
一.配置多数据库 大多数情况下,我们都会采用同一类型的数据库,只是为了缓解压力分成主从或分布式形式而已.声明你可以在 主配置文件 ( main.php ) 中里声明其它的数据库连接: <?p ...
- 详解连接SQL Server数据库的方法,并使用Statement接口实现对数据库的增删改操作
总结一下,连接SQL Server数据库需要以下几个步骤: 1. 导入驱动Jar包:sqljdbc.jar 2. 加载并注册驱动程序 3. 设置连接路径 4. 加载并注册驱动 5. 连接数据库 6. ...
- Unity 3D游戏开发学习路线(方法篇)
Unity 3D本来是由德国的一些苹果粉丝开发的一款游戏引擎,一直只能用于Mac平台,所以一直不被业外人士所知晓.但是后来也推出了2.5版,同时发布了PC版本,并将其发布方向拓展到手持移动设备.Uni ...
- 可遇不可求的Question之导入mysql中文乱码解决方法篇
可遇不可求的Question之导入mysql中文乱码解决方法篇 先 set names utf8;然后 source c:\1.sql ?
- Java+Selenium3方法篇24-单选和多选按钮操作
Java+Selenium3方法篇24-单选和多选按钮操作 本篇介绍 webdriver处理前端单选按钮的操作.单选按钮一般叫raido button,就像我们在电子版的单选答题过程一样,单选只能点击 ...
- Java Learning Path(四) 方法篇
Java Learning Path(四) 方法篇 Java作为一门编程语言,最好的学习方法就是写代码.当你学习一个类以后,你就可以自己写个简单的例子程序来运行一下,看看有什么结果,然后再多调用几个类 ...
- .NET Core 获取数据库上下文实例的方法和配置连接字符串
目录 .NET Core 获取数据库上下文实例的方法和配置连接字符串 ASP.NET Core 注入 .NET Core 注入 无签名上下文 OnConfigure 配置 有签名上下文构造函数和自己n ...
- delphi 连接各中数据库方法
---恢复内容开始--- 数据库连接字符串的拼写规则的决定条件: • 连接的数据库的类型:SQL Server,Oracle,MySQL,Acess,MogoDB,Visual FoxPro(dBAS ...
- plsql连接本地oracle数据库,而远程主机却无法连接,出现无监听程序的解决方法(转)
原文转自:plsql连接本地oracle数据库,而远程主机却无法连接,出现无监听程序的解决方法 最近在使用plsql连接本地oracle数据库的时候,在同一网络环境中,出现了可以连接本地oracle, ...
随机推荐
- JDK篇
卸载系统自带的jdk 使用以下命令查看是否已经安装了jdk rpm -qa|grep java rpm -qa|grep jdk 如果已经安装了可能会得到下面的结果: java-1.4.2-gcj ...
- 写给在Java和.net中徘徊的新手
在很多网站上,网友都会问一个相同的问题,到底是学Java还是.net,个有个的见解. 自从.Net问世以来,程序员都很关心的一个问题是「该学Java或.NET」.我也在挣扎,该「该继续Java的研究, ...
- linux常用命令集锦
linux 查看所有用户所在组 vi /etc/group 一个用户可以属于多个组,查看用户所属的组,groups + 用户名 linux 查找文件命令 find -name 文件名 在 ...
- andriod 文本居中: android:gravity="center"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&q ...
- ngx_lua实现登录逻辑
最近在公司做一个简单的portal,本来很简单的,只用ngx_lua就可以实现所有的业务逻辑,不需要upstream上游服务.但被要求接入公司内部的用户校验系统,说白了就是一个登录过程,只允许公司内部 ...
- JDBC结合JSP使用(1)
1. 添加数据 在jsp页面中添加数据,和在serv中添加数据相似.获得页面中提交的数据以后,把数据保存到数据库表中,JSP的代码如下: add.jsp <%@ page language=&q ...
- 第七章 常用Java集合类总结
7.1.List(允许重复元素) ArrayList: 底层数据结构:Object[] 在查询(get).遍历(iterator).修改(set)使用的比较多的情况下,用ArrayList 可扩容,容 ...
- go语言基础之切片做函数参数
1.切片做函数参数 (备注:用了冒泡排序) 示例: package main //必须有个main包 import "fmt" import "math/rand&quo ...
- Python并发编程-进程 线程 同步锁 线程死锁和递归锁
进程是最小的资源单位,线程是最小的执行单位 一.进程 进程:就是一个程序在一个数据集上的一次动态执行过程. 进程由三部分组成: 1.程序:我们编写的程序用来描述进程要完成哪些功能以及如何完成 2.数据 ...
- Maximal Rectangle leetcode java
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...