# [數據庫工廠類](http://codeigniter.org.cn/user_guide/database/forge.html#id16)
數據庫工廠類提供了一些方法來幫助你管理你的數據庫。
Table of Contents
[TOC=2,3]
## 初始化數據庫工廠類
重要
由于數據庫工廠類依賴于數據庫驅動器,為了初始化該類,你的數據庫驅動器必須已經運行。
加載數據庫工廠類的代碼如下:
~~~
$this->load->dbforge()
~~~
如果你想管理的不是你正在使用的數據庫,你還可以傳另一個數據庫對象到數據庫工具類的加載方法:
~~~
$this->myforge = $this->load->dbforge($this->other_db, TRUE);
~~~
上例中,我們通過第一個參數傳遞了一個自定義的數據庫對象,第二個參數表示方法將返回 dbforge 對象, 而不是直接賦值給?$this->dbforge?。
注解
兩個參數都可以獨立使用,如果你只想傳第二個參數,可以將第一個參數置空。
一旦初始化結束,你就可以使用?$this->dbforge?對象來訪問它的方法:
~~~
$this->dbforge->some_method();
~~~
## 創建和刪除數據庫
**$this->dbforge->create_database('db_name')**
用于創建指定數據庫,根據成敗返回 TRUE 或 FALSE
~~~
if ($this->dbforge->create_database('my_db'))
{
echo 'Database created!';
}
~~~
**$this->dbforge->drop_database('db_name')**
用于刪除指定數據庫,根據成敗返回 TRUE 或 FALSE
~~~
if ($this->dbforge->drop_database('my_db'))
{
echo 'Database deleted!';
}
~~~
## 創建和刪除數據表
創建表涉及到這樣幾件事:添加字段、添加鍵、修改字段。CodeIgniter 提供了這幾個方法。
### 添加字段
字段通過一個關聯數組來創建,數組中必須包含一個 'type' 索引,代表字段的數據類型。 例如,INT、VARCHAR、TEXT 等,有些數據類型(例如 VARCHAR)還需要加一個 'constraint' 索引。
~~~
$fields = array(
'users' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
);
// will translate to "users VARCHAR(100)" when the field is added.
~~~
另外,還可以使用下面的鍵值對:
* unsigned/true : 在字段定義中生成 "UNSIGNED"
* default/value : 在字段定義中生成一個默認值
* null/true : 在字段定義中生成 "NULL" ,如果沒有這個,字段默認為 "NOT NULL"
* auto_increment/true : 在字段定義中生成自增標識,注意數據類型必須支持這個,譬如整型
~~~
$fields = array(
'blog_id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'blog_title' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'blog_author' => array(
'type' =>'VARCHAR',
'constraint' => '100',
'default' => 'King of Town',
),
'blog_description' => array(
'type' => 'TEXT',
'null' => TRUE,
),
);
~~~
字段定義好了之后,就可以在調用?create_table()?方法的后面使用?$this->dbforge->add_field($fields);?方法來添加字段了。
**$this->dbforge->add_field()**
添加字段方法的參數就是上面介紹的數組。
#### 使用字符串參數添加字段
如果你非常清楚的知道你要添加的字段,你可以使用字段的定義字符串來傳給 add_field() 方法
~~~
$this->dbforge->add_field("label varchar(100) NOT NULL DEFAULT 'default label'");
~~~
注解
多次調用 add_field() 將會累積
#### 創建 id 字段
創建 id 字段和創建其他字段非常不一樣,id 字段將會自動定義成類型為 INT(9) 的自增主鍵。
~~~
$this->dbforge->add_field('id');
// gives id INT(9) NOT NULL AUTO_INCREMENT
~~~
### 添加鍵
通常來說,表都會有鍵。這可以使用 $this->dbforge->add_key('field') 方法來實現。 第二個參數可選,可以將其設置為主鍵。注意 add_key() 方法必須緊跟在 create_table() 方法的后面。
包含多列的非主鍵必須使用數組來添加,下面是 MySQL 的例子。
~~~
$this->dbforge->add_key('blog_id', TRUE);
// gives PRIMARY KEY `blog_id` (`blog_id`)
$this->dbforge->add_key('blog_id', TRUE);
$this->dbforge->add_key('site_id', TRUE);
// gives PRIMARY KEY `blog_id_site_id` (`blog_id`, `site_id`)
$this->dbforge->add_key('blog_name');
// gives KEY `blog_name` (`blog_name`)
$this->dbforge->add_key(array('blog_name', 'blog_label'));
// gives KEY `blog_name_blog_label` (`blog_name`, `blog_label`)
~~~
### 創建表
字段和鍵都定義好了之后,你可以使用下面的方法來創建表:
~~~
$this->dbforge->create_table('table_name');
// gives CREATE TABLE table_name
~~~
第二個參數設置為 TRUE ,可以在定義中添加 "IF NOT EXISTS" 子句。
~~~
$this->dbforge->create_table('table_name', TRUE);
// gives CREATE TABLE IF NOT EXISTS table_name
~~~
你還可以指定表的屬性,譬如 MySQL 的?ENGINE
~~~
$attributes = array('ENGINE' => 'InnoDB');
$this->dbforge->create_table('table_name', FALSE, $attributes);
// produces: CREATE TABLE `table_name` (...) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
~~~
注解
除非你指定了?CHARACTER?SET?或?COLLATE?屬性,create_table()?方法 默認會使用配置文件中?char_set?和?dbcollat?的值(僅針對 MySQL)。
### 刪除表
執行一個 DROP TABLE 語句,可以選擇添加 IF EXISTS 子句。
~~~
// Produces: DROP TABLE table_name
$this->dbforge->drop_table('table_name');
// Produces: DROP TABLE IF EXISTS table_name
$this->dbforge->drop_table('table_name',TRUE);
~~~
### [重命名表](http://codeigniter.org.cn/user_guide/database/forge.html#id24)
執行一個重命名表語句。
~~~
$this->dbforge->rename_table('old_table_name', 'new_table_name');
// gives ALTER TABLE old_table_name RENAME TO new_table_name
~~~
## 修改表
### 給表添加列
**$this->dbforge->add_column()**
add_column()?方法用于對現有數據表進行修改,它的參數和上面介紹的 字段數組一樣。
~~~
$fields = array(
'preferences' => array('type' => 'TEXT')
);
$this->dbforge->add_column('table_name', $fields);
// Executes: ALTER TABLE table_name ADD preferences TEXT
~~~
如果你使用 MySQL 或 CUBIRD ,你可以使用 AFTER 和 FIRST 語句來為新添加的列指定位置。
例如:
~~~
// Will place the new column after the `another_field` column:
$fields = array(
'preferences' => array('type' => 'TEXT', 'after' => 'another_field')
);
// Will place the new column at the start of the table definition:
$fields = array(
'preferences' => array('type' => 'TEXT', 'first' => TRUE)
);
~~~
### 從表中刪除列
**$this->dbforge->drop_column()**
用于從表中刪除指定列。
~~~
$this->dbforge->drop_column('table_name', 'column_to_drop');
~~~
### 修改表中的某個列
**$this->dbforge->modify_column()**
該方法的用法和?add_column()?一樣,只是它用于對現有的列進行修改,而不是添加新列。 如果要修改列的名稱,你可以在列的定義數組中添加一個 "name" 索引。
~~~
$fields = array(
'old_name' => array(
'name' => 'new_name',
'type' => 'TEXT',
),
);
$this->dbforge->modify_column('table_name', $fields);
// gives ALTER TABLE table_name CHANGE old_name new_name TEXT
~~~
## 類參考
classCI_DB_forge
add_column($table[,?$field = array()[,?$_after = NULL]])
參數:
* **$table**?(string) -- Table name to add the column to
* **$field**?(array) -- Column definition(s)
* **$_after**?(string) -- Column for AFTER clause (deprecated)
返回: TRUE on success, FALSE on failure
返回類型: bool
給表添加列。用法參見?[給表添加列](http://codeigniter.org.cn/user_guide/database/forge.html#id12)?。
add_field($field)
參數:
* **$field**?(array) -- Field definition to add
返回: CI_DB_forge instance (method chaining)
返回類型: CI_DB_forge
添加字段到集合,用于創建一個表。用法參見?[添加字段](http://codeigniter.org.cn/user_guide/database/forge.html#id5)?。
add_key($key[,?$primary = FALSE])
參數:
* **$key**?(array) -- Name of a key field
* **$primary**?(bool) -- Set to TRUE if it should be a primary key or a regular one
返回: CI_DB_forge instance (method chaining)
返回類型: CI_DB_forge
添加鍵到集合,用于創建一個表。用法參見:[添加鍵](http://codeigniter.org.cn/user_guide/database/forge.html#id7)?。
create_database($db_name)
參數:
* **$db_name**?(string) -- Name of the database to create
返回: TRUE on success, FALSE on failure
返回類型: bool
創建數據庫。用法參見:[創建和刪除數據庫](http://codeigniter.org.cn/user_guide/database/forge.html#id3)?。
create_table($table[,?$if_not_exists = FALSE[,?array $attributes = array()]])
參數:
* **$table**?(string) -- Name of the table to create
* **$if_not_exists**?(string) -- Set to TRUE to add an 'IF NOT EXISTS' clause
* **$attributes**?(string) -- An associative array of table attributes
返回: TRUE on success, FALSE on failure
返回類型: bool
創建表。用法參見:[創建表](http://codeigniter.org.cn/user_guide/database/forge.html#id8)?。
drop_column($table,?$column_name)
參數:
* **$table**?(string) -- Table name
* **$column_name**?(array) -- The column name to drop
返回: TRUE on success, FALSE on failure
返回類型: bool
刪除某個表的字段。用法參見:[從表中刪除列](http://codeigniter.org.cn/user_guide/database/forge.html#id13)?。
drop_database($db_name)
參數:
* **$db_name**?(string) -- Name of the database to drop
返回: TRUE on success, FALSE on failure
返回類型: bool
刪除數據庫。用法參見:[創建和刪除數據庫](http://codeigniter.org.cn/user_guide/database/forge.html#id3)?。
drop_table($table_name[,?$if_exists = FALSE])
參數:
* **$table**?(string) -- Name of the table to drop
* **$if_exists**?(string) -- Set to TRUE to add an 'IF EXISTS' clause
返回: TRUE on success, FALSE on failure
返回類型: bool
刪除表。用法參見:[刪除表](http://codeigniter.org.cn/user_guide/database/forge.html#id9)?。
modify_column($table,?$field)
參數:
* **$table**?(string) -- Table name
* **$field**?(array) -- Column definition(s)
返回: TRUE on success, FALSE on failure
返回類型: bool
修改表的某個列。用法參見:[修改表中的某個列](http://codeigniter.org.cn/user_guide/database/forge.html#id14)?。
rename_table($table_name,?$new_table_name)
參數:
* **$table**?(string) -- Current of the table
* **$new_table_name**?(string) -- New name of the table
返回: TRUE on success, FALSE on failure
返回類型: bool
重命名表。用法參見:[重命名表](http://codeigniter.org.cn/user_guide/database/forge.html#id10)?。
- 歡迎使用 CodeIgniter
- 安裝說明
- 下載 CodeIgniter
- 安裝說明
- 從老版本升級
- 疑難解答
- CodeIgniter 概覽
- CodeIgniter 將從這里開始
- CodeIgniter 是什么?
- 支持特性
- 應用程序流程圖
- 模型-視圖-控制器
- 設計與架構目標
- 教程 - 內容提要
- 加載靜態內容
- 讀取新聞條目
- 創建新聞條目
- 結束語
- 常規主題
- CodeIgniter URL
- 控制器
- 保留名稱
- 視圖
- 模型
- 輔助函數
- 使用 CodeIgniter 類庫
- 創建類庫
- 使用 CodeIgniter 驅動器
- 創建驅動器
- 創建核心系統類
- 創建附屬類
- 鉤子 - 擴展框架核心
- 自動加載資源
- 公共函數
- 兼容性函數
- URI 路由
- 錯誤處理
- 網頁緩存
- 程序分析
- 以 CLI 方式運行
- 管理你的應用程序
- 處理多環境
- 在視圖文件中使用 PHP 替代語法
- 安全
- PHP 開發規范
- 類庫參考
- 基準測試類
- 緩存驅動器
- 日歷類
- 購物車類
- 配置類
- Email 類
- 加密類
- 加密類(新版)
- 文件上傳類
- 表單驗證類
- FTP 類
- 圖像處理類
- 輸入類
- Javascript 類
- 語言類
- 加載器類
- 遷移類
- 輸出類
- 分頁類
- 模板解析類
- 安全類
- Session 類
- HTML 表格類
- 引用通告類
- 排版類
- 單元測試類
- URI 類
- 用戶代理類
- XML-RPC 與 XML-RPC 服務器類
- Zip 編碼類
- 數據庫參考
- 數據庫快速入門: 示例代碼
- 數據庫配置
- 連接你的數據庫
- 查詢
- 生成查詢結果
- 查詢輔助函數
- 查詢構造器類
- 事務
- 數據庫元數據
- 自定義函數調用
- 數據庫緩存類
- 數據庫工廠類
- 數據庫工具類
- 數據庫驅動器參考
- 輔助函數參考
- 數組輔助函數
- 驗證碼輔助函數
- Cookie 輔助函數
- 日期輔助函數
- 目錄輔助函數
- 下載輔助函數
- 郵件輔助函數
- 文件輔助函數
- 表單輔助函數
- HTML 輔助函數
- 語言輔助函數
- Inflector 輔助函數
- 數字輔助函數
- 路徑輔助函數
- 安全輔助函數
- 表情輔助函數
- 字符串輔助函數
- 文本輔助函數
- 排版輔助函數
- URL 輔助函數
- XML 輔助函數
- 向 CodeIgniter 貢獻你的力量